【问题标题】:Reporting app crashes and exceptions to a particular Web service in iOS向 iOS 中的特定 Web 服务报告应用程序崩溃和异常
【发布时间】:2026-01-15 15:20:08
【问题描述】:
有人告诉我,即使是从应用程序的发布版本,也要以自定义方式将该信息发送到 REST 服务……最好的方法是什么?将信息保存到文件中并在应用关闭之前发送?您是否应该请求用户允许报告错误?
提前致谢
【问题讨论】:
标签:
ios
web-services
exception
crash-reports
【解决方案1】:
我正在使用开源PLCrashReporter。
步骤是:
下载框架并将其导入您的项目。
-
在你的 applicationDidFinish...:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Crash Reports
PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
if ([crashReporter hasPendingCrashReport]) [self handleCrashReport];
[crashReporter enableCrashReporterAndReturnError:nil];
...
}
-
在您的 AppDelegate.m 中添加以下方法:
#pragma mark - Crash Reports
- (void)handleCrashReport
{
PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
NSData *crashData;
NSError *error;
crashData = [crashReporter loadPendingCrashReportDataAndReturnError:&error];
PLCrashReport *report = [[PLCrashReport alloc] initWithData:crashData error:nil];
if (!crashData || !report) {
[crashReporter purgePendingCrashReport];
} else {
NSString *stringRepresentation = [PLCrashReportTextFormatter stringValueForCrashReport:report withTextFormat:PLCrashReportTextFormatiOS];
[self sendDataOnLatestCrashToServer:stringRepresentation];
[crashReporter purgePendingCrashReport];
}
}
- (void)sendDataOnLatestCrashToServer:(NSString *)crashString
{
NSDictionary *params = @{
@"StackTrace" : crashString
// Add more parameters as you want
};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:@"http://www.YOURRESTSERVER.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0f];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
}];
}
请注意,堆栈跟踪将仅在下一次应用启动时发送到服务器(由于 iOS 限制)。