我不知道为什么我的应用程序在此行崩溃
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
这是我的代码:
NSString * urlString = [[NSUserDefaults standardUserDefaults] objectForKey:MAINURL];
NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest *request;
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:120];
if([[[NSUserDefaults standardUserDefaults] objectForKey:@"callWebServiceFor"] isEqualToString:nil]) {
// [request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
NSString * strSessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
if(strSessionId != nil)
[request setValue:strSessionId forHTTPHeaderField:@"Cookie"];
}
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Storing session headers when user logs in successfully
if([[[NSUserDefaults standardUserDefaults] objectForKey:@"callWebServiceFor"] isEqualToString:@"login"]) {
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:urlString]]; //testing
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:urlString] mainDocumentURL:nil];
NSString * strSessionId;
for (NSHTTPCookie *cookie in all) {
strSessionId = [[NSString alloc] initWithString:cookie.value];
// NSLog(@"Session value: %@",cookie.key];
// NSLog(@"Session value: %@",strSessionId);
}
[[NSUserDefaults standardUserDefaults] setObject:strSessionId forKey:@"sessionId"];
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"callWebServiceFor"];
}
if (data != nil) {
dispatch_async(kBackGroudQueue, ^{
[self performSelectorOnMainThread:@selector(handleWebServiceResponse:)
withObject:data waitUntilDone:YES];
});
} else {
[SwapweekUtilViewController showAlert:@"Internet" :@"Check your Internet Connection"];
}
答案 0 :(得分:0)
我无法理解为什么您的代码在NSURLConnection sendSynchronousRequest:
崩溃,而且您还没有发布堆栈跟踪来验证这一事实,但是此代码可能会崩溃(如果strSessionId
为{{1} }}):
nil
此代码将崩溃:
[[NSUserDefaults standardUserDefaults] setObject:strSessionId forKey:@"sessionId"];
(使用[[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"callWebServiceFor"];
从用户默认值中删除对象。)
这也很差:
removeObjectForKey:
(代之以if([[[NSUserDefaults standardUserDefaults] objectForKey:@"callWebServiceFor"] isEqualToString:nil]) {
测试。)
这也很糟糕:
[NSString length] == 0
(for (NSHTTPCookie *cookie in all) {
strSessionId = [[NSString alloc] initWithString:cookie.value];
// NSLog(@"Session value: %@",cookie.key];
// NSLog(@"Session value: %@",strSessionId);
}
一旦你有一个非空的break
而只是做strSessionId
而不是那个strSessionId = cookie.key;
。)