標籤:ios 異常 try xcode select
1.iOS
在程式的開發中我們難免會遇到崩潰的問題。然後在使用者體驗的時候,我們如何來防止崩潰的發生呢,並將我們的崩潰原因發送給開發人員來處理它。
來看一個例子
NSString *str = @"523"; arr = @[@"sdad", @"dwada", @"ffwwra"]; [str substringFromIndex:111];
程式這樣寫的時候是絕對會崩潰的。我們如果想它不要崩潰,那麼應該怎麼做呢。
@try { NSString *str = @"523"; arr = @[@"sdad", @"dwada", @"ffwwra"]; [str substringFromIndex:111]; } @catch (NSException *exception) { NSLog(@"%s %@", __FUNCTION__, exception); } @finally { //如何來對待這個異常處理 NSLog(@"tryTwo - 我一定會執行"); }
我們可以使用@try{}@catch(){}@finally來處理,這樣程式在啟動並執行時候就不會崩潰了。而是跑到@finnally這裡邊來處理異常然後在@catch裡邊來列印出崩潰原因
怎麼樣來實現發送給開發人員郵件呢?
在iOS中發送郵件是很簡單的。
封裝來如下方法
//// CRASHBUG.h// try處理異常//// Created by 黃權浩 on 15-1-24.// Copyright (c) 2015年 黃權浩. All rights reserved.//#import <Foundation/Foundation.h>@interface CRASHBUG : NSObject+ (void)sendBug:(NSString *)bug interface:(NSException *)interfaceinfo;@end
//// CRASHBUG.m// try處理異常//// Created by 黃權浩 on 15-1-24.// Copyright (c) 2015年 黃權浩. All rights reserved.//#import "CRASHBUG.h"#import "AppDelegate.h"@implementation CRASHBUG+ (void)sendBug:(NSString *)bug interface:(NSException *)interfaceinfo{ NSTimeInterval time = [[NSDate date] timeIntervalSince1970]; long long int date = (long long int)time; NSDate *dd = [NSDate dateWithTimeIntervalSince1970:date]; NSString *crashLogInfo = [NSString stringWithFormat:@"exception type : %@ \n crash reason : %@ \n call stack time : %@", interfaceinfo, bug, dd]; NSString *urlStr = [NSString stringWithFormat:@"mailto://[email protected]?subject=bug report&body=Thank you for your cooperation!""Error Details:%@",crashLogInfo]; NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; [[UIApplication sharedApplication] openURL:url];}@end然後這麼來使用
//// ViewController.m// try處理異常//// Created by 黃權浩 on 15-1-24.// Copyright (c) 2015年 黃權浩. All rights reserved.//#import "ViewController.h"#import "CRASHBUG.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. @try { NSString *str = @"523"; [str substringFromIndex:111]; } @catch (NSException *exception) { NSLog(@"%s %@", __FUNCTION__, exception); /** * 把異常崩潰資訊發送至開發人員郵件 */ [CRASHBUG sendBug:@"字串的類型轉化" interface:exception]; } @finally { //如何來對待這個異常處理 NSLog(@"tryTwo - 我一定會執行"); }}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
這樣在崩潰的時候就能將郵件發送到開發人員郵箱了
iOS 異常處理,將bug資訊發送到開發人員郵箱