TL;DR: Use Carthage to include https://github.com/eggheadgames/SwiftTryCatch or CocoaPods to include https://github.com/williamFalcon/SwiftTryCatch.
Then you can use code like this without fear it will crash your app:
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
}
}
The accepted answer by @BPCorp works as intended, but as we discovered, things get a little interesting if you try to incorporate this Objective C code into a majority Swift framework and then run tests. We had problems with the class function not being found (Error: Use of unresolved identifier). So, for that reason, and just general ease of use, we packaged it up as a Carthage library for general use.
Strangely, we could use the Swift + ObjC framework elsewhere with no problems, it was just the unit tests for the framework that were struggling.
PRs requested! (It would be nice to have it a combo CocoaPod & Carthage build, as well as have some tests).
NSPredicate(fromMetadataQueryString:)
. This is supposed to be aninit?
, so if the string is bad it is probably intended to returnnil
, but in fact it just crashes with an NSException. – PhotosynthesisNSException
yourself, then easily see how to createNSError
(and throw that, instead ofNSException
) – Dalury