我就是这样做的:而不是
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]
我基于包含的类创建了相同的方法实例,因为我们需要一个委托。并且不要使其成为单例,因此每个连接都有其独立变量,因为如果我们不这样做,并且两个连接恰好在另一个完成之前被调用,那么接收到的数据和循环的处理将不可恢复地交织在一起.
[[ClassNameHere new] sendSynchronousRequest:request returningResponse:&response error:&error]
这样我可以创建一个 NSUrl 连接并处理它(以同步的方式,我们将看到如何)所以我不必更改任何以前编写的代码。
- (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse *__strong*)response error:(NSError *__strong*)error
{
_finishedLoading=NO;
_receivedData=[NSMutableData new];
_error=error;
_response=response;
NSURLConnection*con=[NSURLConnection connectionWithRequest:request delegate:self];
[con start];
CFRunLoopRun();
return _receivedData;
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
//handle the challenge
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
*_response=response;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
*_error=error;
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
CFRunLoopStop(CFRunLoopGetCurrent());
}
诀窍在于 CFRunLoopRun() 和 CFRunLoopStop(CFRunLoopGetCurrent()) 我希望它在未来对其他人有所帮助。