TL; DR: use Carthage to enable https://github.com/eggheadgames/SwiftTryCatch or CocoaPods to enable https://github.com/ravero/SwiftTryCatch .
Then you can use this code without fear that it will crash your application:
import Foundation import SwiftTryCatch class SafeArchiver { class func unarchiveObjectWithFile(filename: String) -> AnyObject? { var data : AnyObject? = nil if NSFileManager.defaultManager().fileExistsAtPath(filename) { SwiftTryCatch.tryBlock({ data = NSKeyedUnarchiver.unarchiveObjectWithFile(filename) }, catchBlock: { (error) in Logger.logException("SafeArchiver.unarchiveObjectWithFile") }, finallyBlock: { }) } return data } class func archiveRootObject(data: AnyObject, toFile : String) -> Bool { var result: Bool = false SwiftTryCatch.tryBlock({ result = NSKeyedArchiver.archiveRootObject(data, toFile: toFile) }, catchBlock: { (error) in Logger.logException("SafeArchiver.archiveRootObject") }, finallyBlock: { }) return result } }
@BPCorp's accepted answer works as intended, but as we found out, things get a little interesting if you try to include this Objective-C code in most Swift structures and then run the tests. We had problems with the lack of a class function (Error: using an unresolved identifier). Therefore, for this reason, and just general ease of use, we packaged it as a Carthage library for general use.
Oddly enough, we could use the Swift + ObjC environment in other places without problems, these were only unit tests for the framework that was struggling.
PR requested! (It would be nice to have his CocoaPod and Carthage build combos, as well as have some tests).
mm2001 Dec 28 '15 at 10:10 2015-12-28 22:10
source share