Đó là cách tôi đã làm nó: thay vì
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]
tôi đã dụ cùng một phương pháp dựa trên lớp chứa, vì chúng ta sẽ cần một đại biểu. Và không làm cho nó trở nên đơn điệu, vì vậy mọi kết nối đều có các biến độc lập của nó, bởi vì, nếu chúng ta không, và hai kết nối xảy ra trước khi kết thúc khác, thì dữ liệu nhận được và xử lý các vòng lặp sẽ được đan xen với nhau .
[[ClassNameHere new] sendSynchronousRequest:request returningResponse:&response error:&error]
Bằng cách này tôi có thể tạo kết nối NSUrl và xử lý nó (theo cách đồng bộ, chúng ta sẽ thấy cách) vì vậy tôi không phải thay đổi bất kỳ mã nào được viết trước đó.
- (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());
}
Bí quyết là ở CFRunLoopRun() và CFRunLoopStop (CFRunLoopGetCurrent()) Tôi hy vọng nó sẽ giúp người khác trong futur.
Anh ấy cần cuộc gọi hàm phụ thuộc thể hiện để cung cấp cho đại biểu phản hồi thử thách https – LolaRun
Cảm ơn bạn :) Thật đơn giản. –