Last active
June 10, 2019 04:06
-
-
Save zhihuitang/6d3de0963d96a552d47721a598ca79c8 to your computer and use it in GitHub Desktop.
How to properly catch NSExceptions in Swift?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// OCCatch.h | |
// | |
// | |
#ifndef OCCatch_h | |
#define OCCatch_h | |
// add the code below to your -Bridging-Header.h | |
/** | |
#import "OCCatch.h" | |
*/ | |
// How to use it in Swift? | |
/** | |
let exception = tryBlock { | |
let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView | |
//...... | |
} | |
if let exception = exception { | |
print("exception: \(exception)") | |
} | |
*/ | |
#import <Foundation/Foundation.h> | |
NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) { | |
@try { | |
tryBlock(); | |
} | |
@catch (NSException *exception) { | |
return exception; | |
} | |
return nil; | |
} | |
#endif /* OCCatch_h */ |
Hi @sukh1993,
The reason is that in Swift project, sometimes the crash happens in the Objective-C side, we cannot use try { } catch { }
to catch Objective-C crash. In that case we have to use a Objective-C wrapper to catch it.
For example: https://stackoverflow.com/questions/44167577/using-private-api-to-read-wifi-rssi-value/48083845?noredirect=1#comment88290822_48083845
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello sir ,
can u explain me why we use this bridge file