Ale*_*exR 11 cocoa objective-c nsurlrequest ios
我使用iOS7的新URL请求方法获取数据,如下所示:
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:[self.baseUrl
stringByAppendingString:path]]];
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSUInteger responseStatusCode = [httpResponse statusCode];
if (responseStatusCode != 200) {
// RETRY (??????)
} else
completionBlock(results[@"result"][symbol]);
}];
[dataTask resume];
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不时收到HTTP响应,表明服务器无法访问(response code != 200
)并需要向服务器重新发送相同的请求.
如何才能做到这一点?我如何完成上面评论所在的代码片段// RETRY
?
在我的示例中,我在成功获取后调用完成块.但是如何再次发送相同的请求呢?
谢谢!
Avt*_*Avt 16
最好有一个重试计数器来防止你的方法永远运行:
- (void)someMethodWithRetryCounter:(int) retryCounter
{
if (retryCounter == 0) {
return;
}
retryCounter--;
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:[self.baseUrl
stringByAppendingString:path]]];
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSUInteger responseStatusCode = [httpResponse statusCode];
if (responseStatusCode != 200) {
[weakSelf someMethodWithRetryCounter: retryCounter];
} else
completionBlock(results[@"result"][symbol]);
}];
[dataTask resume];
}
Run Code Online (Sandbox Code Playgroud)
应按以下方式调用:
[self someMethodWithRetryCounter:5];
Run Code Online (Sandbox Code Playgroud)
Mat*_*bbi 13
将您的请求代码放在方法中,然后在dispatch_async
块中再次调用它;)
- (void)requestMethod {
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:[self.baseUrl
stringByAppendingString:path]]];
__weak typeof (self) weakSelf = self;
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSUInteger responseStatusCode = [httpResponse statusCode];
if (responseStatusCode != 200) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
[weakSelf requestMethod];
});
} else
completionBlock(results[@"result"][symbol]);
}];
[dataTask resume];
}
Run Code Online (Sandbox Code Playgroud)