Last active
April 22, 2019 08:40
-
-
Save externvoid/84dabc971dbc06290b06a2e31fe6fb25 to your computer and use it in GitHub Desktop.
Uncaught Exceptionをlogへ保存する
This file contains hidden or 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
// case 1 | |
//AppDelegate#application:didFinishLaunchingWithOptions | |
NSSetUncaughtExceptionHandler {e in | |
print(">>>>> ExceptionHandler OK") | |
let log = NSString(format:"%@, %@", e.name, e.reason!) | |
NSUserDefaults.standardUserDefaults().setValue(log, forKey: "failLog") | |
} | |
// case 2 | |
// Closureを渡さなくても、swift関数の関数名を渡しても良い。ただし、NSSetUncaughtExceptionHandlerと同じスコープ内に | |
// swift関数が無いとコンパイルエラー⁉️ | |
func exceptionHandler( exception: NSException) { | |
print("exceptionHandler func2") | |
let log = NSString(format:"%@, %@, %@", exception.name, exception.reason!, exception.callStackSymbols) | |
NSUserDefaults.standardUserDefaults().setValue(log, forKey: "failLog") | |
} | |
NSSetUncaughtExceptionHandler(exceptionHandler) | |
// case 3 | |
// swiftの関数ではなくObj-Cの関数を渡す事もできる。 | |
// Uncaught.m | |
#import "Uncaught.h" | |
// How should I use NSSetUncaughtExceptionHandler in Swift - Stack Overflow | |
volatile void exceptionHandler(NSException *exception) { | |
NSLog(@"in Obj-C exceptionHandler"); | |
NSString *log = [NSString stringWithFormat:@"%@, %@", exception.name, exception.reason]; | |
// NSString *log = [NSString stringWithFormat:@"%@, %@, %@", exception.name, exception.reason, exception.callStackSymbols]; | |
[[NSUserDefaults standardUserDefaults] setValue:log forKey:@"failLog"]; | |
} | |
NSUncaughtExceptionHandler *exceptionHandlerPtr = &exceptionHandler; | |
// Uncaught.h | |
#import <Foundation/Foundation.h> | |
extern NSUncaughtExceptionHandler *exceptionHandlerPtr;//Swiftに公開する変数だよ! | |
volatile void exceptionHandler(NSException *exceptionHandlerPtr);//mファイルで実装必要な関数だよ! | |
//ErrHandle-Bridging-Header.h | |
// | |
// Use this file to import your target's public headers that you would like to expose to Swift. | |
// | |
#import "Uncaught.h" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
⭕️UnCaughtedExceptionを検出するには?⁉️
NSSetUncaughtedExceptionHandlerを呼べば良い。こいつに与えるclosureにはNSErrorオブジェクトが飛んで来る。こいつをUserDeafaultへ保存すれば良い。
こんな感じ
How should I use NSSetUncaughtExceptionHandler in Swift
http://stackoverflow.com/questions/25441302/how-should-i-use-nssetuncaughtexceptionhandler-in-swift