NSURLConnection
中有NSOperation
。此NSOperation
位于NSOperationQueue
。所以,我想知道,如果NSOperation
如果NSURLConnection
因干净代码而失败,该如何回忆NSURLConnection
。
(我想说在下载期间{{1}}失败的情况下)
答案 0 :(得分:1)
现有的开源库可以为您做很多事情。这是AFNetworking。
更重要的是,您经常使用的课程AFURLConnectionOperation
本身就是NSOperation
的子类。
您使用块来设置AFURLConnectionOperation
将执行的代码:
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
- (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace))block;
- (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
只需将AFURLConnectionOperation
正常添加到NSOperationQueue
。
AFHTTPRequestOperation
也很有用。它是使用AFHTTPClient
和NSMutableURLRequest
:
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://www.google.com"]];
NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:nil parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
成功或失败很容易,再次,它处理新的时尚块而不是旧学校代表回调:
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * request, id response)
{
// ... my success block
}
failure:^(AFHTTPRequestOperation *request, NSError *error)
{
// ... my failure block
}];