1

我有一个NSURLConnectionNSOperation. 这NSOperation是在NSOperationQueue. 所以,我想知道,如何用干净的代码召回NSOperationifNSURLConnection失败。(我想说的是,NSURLConnection例如在下载过程中失败的情况下)

4

1 回答 1

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也非常有用。它是用AFHTTPClientand创建的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
 }];
于 2012-09-12T14:17:43.120 回答