如果失败,请使用NSURLConnection调用NSOperation

时间:2012-08-18 02:05:35

标签: objective-c nsurlconnection nsoperation nsoperationqueue

NSURLConnection中有NSOperation。此NSOperation位于NSOperationQueue。所以,我想知道,如果NSOperation如果NSURLConnection因干净代码而失败,该如何回忆NSURLConnection。 (我想说在下载期间{{1}}失败的情况下)

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也很有用。它是使用AFHTTPClientNSMutableURLRequest

创建的
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
 }];