【发布时间】:2014-07-03 11:21:02
【问题描述】:
我正在使用 NSURLConnection 向服务器发送请求,它工作了 2 次,因为第三次它不工作,delegates 没有被调用。我在调试过程中发现connectionShouldUseCredentialStorage方法在初始时被调用,第三次没有被调用,其余的方法也没有被调用。
这是我的代码:
NSString *requestString = [NSString stringWithFormat:@"%@", [serviceParameters JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strUrl]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setHTTPBody:requestData];
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
[self.data appendData:aData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
SBJSON *jsonParser = [[SBJSON new] autorelease];
NSString *jsonString = [[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding] autorelease];
NSError *outError = nil;
id result = [jsonParser objectWithString:jsonString error:&outError];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if( [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust] )
{
return YES;
}
return NO;
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return YES;
}
【问题讨论】:
-
你试过在 NSURL 委托方法中设置断点吗?你也可以尝试增加超时时间。
-
能否检查返回的NSURLConnection是否不是nil,if([NSURLConnection connectionWithRequest:urlRequest delegate:self] != nil) { NSLog(@"connectgion started"); }
-
您是从主线程运行它,还是从连接到运行循环的线程运行它?根据文档:“委托方法在调用此方法的同一线程上调用。要使连接正常工作,调用线程的运行循环必须在默认运行循环模式下运行。”
-
@user2071152 我尝试使用断点并尝试使用超时 300 值,但无助于解决问题。
-
@satheeshwaran:我试过你的代码,它显示连接已启动。 NSURLConnection 不为零。
标签: ios iphone ios7 nsurlconnection nsurlconnectiondelegate