iOS中程序異常Crash友好化處理詳解
前言
前兩天接到個(gè)面試,面試官問到上線的app怎么避免閃退,首先想到的就是在編碼的時(shí)候進(jìn)行各種容錯(cuò),但貌似并不是面試官想要的答案,所以表現(xiàn)的很糟糕。今天有時(shí)間就來整理一下,希望有所幫助。
實(shí)現(xiàn)效果如圖:

效果實(shí)現(xiàn):

用法:
1.將截圖的中CatchedHelper文件夾拖到你的項(xiàng)目工程中。
2.在AppDelegate.m中找到以下方法并如下添加代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[UncaughtExceptionHandler installUncaughtExceptionHandler:YES showAlert:YES];
return YES;
}
以上代碼就可以實(shí)現(xiàn)稍微友好一點(diǎn)的crash攔截處理。
代碼解釋:
UncaughtExceptionHandler.h主要代碼:
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface UncaughtExceptionHandler : NSObject /*! * 異常的處理方法 * * @param install 是否開啟捕獲異常 * @param showAlert 是否在發(fā)生異常時(shí)彈出alertView */ + (void)installUncaughtExceptionHandler:(BOOL)install showAlert:(BOOL)showAlert; @end
UncaughtExceptionHandler.m文件主要的代碼如下:
1.發(fā)送異常信號(hào)
/*
* 異常的處理方法
*
* @param install 是否開啟捕獲異常
* @param showAlert 是否在發(fā)生異常時(shí)彈出alertView
*/
+ (void)installUncaughtExceptionHandler:(BOOL)install showAlert:(BOOL)showAlert {
if (install && showAlert) {
[[self alloc] alertView:showAlert];
}
NSSetUncaughtExceptionHandler(install ? HandleException : NULL);
signal(SIGABRT, install ? SignalHandler : SIG_DFL);
signal(SIGILL, install ? SignalHandler : SIG_DFL);
signal(SIGSEGV, install ? SignalHandler : SIG_DFL);
signal(SIGFPE, install ? SignalHandler : SIG_DFL);
signal(SIGBUS, install ? SignalHandler : SIG_DFL);
signal(SIGPIPE, install ? SignalHandler : SIG_DFL);
}
產(chǎn)生上述的signal的時(shí)候就會(huì)調(diào)用我們定義的SignalHandler來處理異常。
ps: NSSetUncaughtExceptionHandler就是iOS SDK中提供的一個(gè)現(xiàn)成的函數(shù),用來捕獲異常的方法,使用方便。但它不能捕獲拋出的signal,所以定義了SignalHandler方法。
2.處理異常
void HandleException(NSException *exception) {
int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);
// 如果太多不用處理
if (exceptionCount > UncaughtExceptionMaximum) {
return;
}
//獲取調(diào)用堆棧
NSArray *callStack = [exception callStackSymbols];
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];
[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];
//在主線程中,執(zhí)行制定的方法, withObject是執(zhí)行方法傳入的參數(shù)
[[[UncaughtExceptionHandler alloc] init]
performSelectorOnMainThread:@selector(handleException:)
withObject:
[NSException exceptionWithName:[exception name]
reason:[exception reason]
userInfo:userInfo]
waitUntilDone:YES];
}
該方法就是對(duì)應(yīng)NSSetUncaughtExceptionHandler的處理,只要方法關(guān)聯(lián)到這個(gè)函數(shù),那么發(fā)生相應(yīng)錯(cuò)誤時(shí)會(huì)自動(dòng)調(diào)用該函數(shù),調(diào)用時(shí)會(huì)傳入exception參數(shù)。獲取異常后會(huì)將捕獲的異常傳入最終調(diào)用處理的handleException函數(shù)。
3.無法捕獲的signal處理
//處理signal報(bào)錯(cuò)
void SignalHandler(int signal) {
int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);
// 如果太多不用處理
if (exceptionCount > UncaughtExceptionMaximum) {
return;
}
NSString* description = nil;
switch (signal) {
case SIGABRT:
description = [NSString stringWithFormat:@"Signal SIGABRT was raised!\n"];
break;
case SIGILL:
description = [NSString stringWithFormat:@"Signal SIGILL was raised!\n"];
break;
case SIGSEGV:
description = [NSString stringWithFormat:@"Signal SIGSEGV was raised!\n"];
break;
case SIGFPE:
description = [NSString stringWithFormat:@"Signal SIGFPE was raised!\n"];
break;
case SIGBUS:
description = [NSString stringWithFormat:@"Signal SIGBUS was raised!\n"];
break;
case SIGPIPE:
description = [NSString stringWithFormat:@"Signal SIGPIPE was raised!\n"];
break;
default:
description = [NSString stringWithFormat:@"Signal %d was raised!",signal];
}
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
NSArray *callStack = [UncaughtExceptionHandler backtrace];
[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];
[userInfo setObject:[NSNumber numberWithInt:signal] forKey:UncaughtExceptionHandlerSignalKey];
//在主線程中,執(zhí)行指定的方法, withObject是執(zhí)行方法傳入的參數(shù)
[[[UncaughtExceptionHandler alloc] init]
performSelectorOnMainThread:@selector(handleException:)
withObject:
[NSException exceptionWithName:UncaughtExceptionHandlerSignalExceptionName
reason: description
userInfo: userInfo]
waitUntilDone:YES];
}
以上方法是對(duì)于捕獲不到的signal信號(hào)進(jìn)行處理,列出常見的異常類型。
4.堆棧調(diào)用
//獲取調(diào)用堆棧
+ (NSArray *)backtrace {
//指針列表
void* callstack[128];
//backtrace用來獲取當(dāng)前線程的調(diào)用堆棧,獲取的信息存放在這里的callstack中
//128用來指定當(dāng)前的buffer中可以保存多少個(gè)void*元素
//返回值是實(shí)際獲取的指針個(gè)數(shù)
int frames = backtrace(callstack, 128);
//backtrace_symbols將從backtrace函數(shù)獲取的信息轉(zhuǎn)化為一個(gè)字符串?dāng)?shù)組
//返回一個(gè)指向字符串?dāng)?shù)組的指針
//每個(gè)字符串包含了一個(gè)相對(duì)于callstack中對(duì)應(yīng)元素的可打印信息,包括函數(shù)名、偏移地址、實(shí)際返回地址
char **strs = backtrace_symbols(callstack, frames);
int i;
NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
for (i = 0; i < frames; i++) {
[backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
}
free(strs);
return backtrace;
}
backtrace是Linux下用來追蹤函數(shù)調(diào)用堆棧以及定位段錯(cuò)誤的函數(shù)。
5.使用UIAlerView進(jìn)行友好化提示
- (void)handleException:(NSException *)exception {
[self validateAndSaveCriticalApplicationData:exception];
if (!showAlertView) {
return;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIAlertView *alert =
[[UIAlertView alloc]
initWithTitle:@"出錯(cuò)啦"
message:[NSString stringWithFormat:@"你可以嘗試?yán)^續(xù)操作,但是應(yīng)用可能無法正常運(yùn)行.\n"]
delegate:self
cancelButtonTitle:@"退出"
otherButtonTitles:@"繼續(xù)", nil];
[alert show];
#pragma clang diagnostic pop
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
while (!self.dismissed) {
//點(diǎn)擊繼續(xù)
for (NSString *mode in (__bridge NSArray *)allModes) {
//快速切換Mode
CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);
}
}
//點(diǎn)擊退出
CFRelease(allModes);
NSSetUncaughtExceptionHandler(NULL);
signal(SIGABRT, SIG_DFL);
signal(SIGILL, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGFPE, SIG_DFL);
signal(SIGBUS, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName]) {
kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);
} else {
[exception raise];
}
}
在這里你可以做自己的crash收集操作,例如上傳服務(wù)器等。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
iOS之Https自簽名證書認(rèn)證及數(shù)據(jù)請(qǐng)求的封裝原理
本篇文章主要介紹了iOS之Https自簽名證書認(rèn)證及數(shù)據(jù)請(qǐng)求的封裝原理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-02-02
Flutter?Module添加到iOS項(xiàng)目示例詳解
這篇文章主要為大家介紹了Flutter?Module添加到iOS項(xiàng)目示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
iOS UIBezierPath實(shí)現(xiàn)餅狀圖
這篇文章主要為大家詳細(xì)介紹了iOS UIBezierPath實(shí)現(xiàn)餅狀圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-03-03
針對(duì)iOS開發(fā)的一些Xcode使用技巧小結(jié)
這篇文章主要介紹了針對(duì)iOS開發(fā)的一些Xcode使用技巧小結(jié),Xcode是Mac上編寫iOS應(yīng)用的開發(fā)環(huán)境,需要的朋友可以參考下2015-12-12
iOS實(shí)現(xiàn)第三方微信登錄方式實(shí)例解析(最新最全)
這篇文章主要介紹了iOS實(shí)現(xiàn)第三方微信登錄方式實(shí)例解析(最新最全),非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-12-12
iOS開發(fā)中實(shí)現(xiàn)一個(gè)簡單的圖片瀏覽器的實(shí)例講解
這篇文章主要介紹了iOS開發(fā)中實(shí)現(xiàn)一個(gè)簡單的圖片瀏覽器的實(shí)例講解,代碼基礎(chǔ)傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-01-01

