我正在使用下面的代码从网上下载一个文件。如何构造代码(使用块),以便如果代码失败,将以最大重试次数重试。下面是我用来下载文件的代码。
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *myURL = [NSURL URLWithString:@"urlstring"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
[request setValue:token forHTTPHeaderField:@"Authorization"];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *directoryURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
return [directoryURL URLByAppendingPathComponent:fileName];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//check here if error then retry using block ?
if (!error)
{
//do something with the file
}
else
{
//retry download ??
}
}
}];
[downloadTask resume];发布于 2015-07-07 21:19:54
您可以创建一个retryCount实例变量,并将其设置为要重试网络调用的多少次。然后,可以将所有网络代码放入具有自定义完成处理程序的方法中。完成处理程序可以是一个以BOOL作为参数并返回void的块。然后,在网络代码中,创建一个本地BOOL变量,并根据网络调用是否成功将其设置为YES或NO。您将在网络代码中运行完成处理程序参数。然后,作为参数发送给方法的块(完成处理程序)可以“查看”方法中的局部变量是设置为YES还是NO。如果是YES,网络调用就成功了,所以什么也不做。如果是NO,则网络调用失败,所以请检查retryCount--如果它> 0,再次调用网络方法并减少retryCount。
更新
这应该给你一个粗略的想法..。
typedef void (^CustomCompletionHandler)(BOOL); // Create your CustomCompletionHandler type
- (void)getDataAndCallCompletionHandler:(CustomCompletionHandler *)completionHandler {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *myURL = [NSURL URLWithString:@"urlstring"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
[request setValue:token forHTTPHeaderField:@"Authorization"];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
BOOL success = NO; // Create local variable to keep track of whether network call succeeded or failed
NSURL *directoryURL = [NSURL fileURLWithPath:NSTemporaryDirectory()];
return [directoryURL URLByAppendingPathComponent:fileName];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//check here if error then retry using block ?
if (!error)
{
success = YES;
//do something with the file
}
else
{
success = NO;
//retry download ??
}
}
// Get main queue and call completionHandler and pass success:
// completionHandler(success)
}];
[downloadTask resume];
}你可以通过做这样的事情来调用这个方法。
[self getDataAndCallCompletionHandler:^(BOOL success) {
// If success == true {
// Do whatever you need to
// } else {
// Check retryCount
// If you need to, call getDataAndCallCompletionHandler: again
// }
}];https://stackoverflow.com/questions/31279099
复制相似问题