iOS 对于下载请求超时重新下载的方法

  • Post author:
  • Post category:其他


在批量下载图片的时候,部分图片总是请求超时,于是想到的超时重新下载的方法

- (void)downloadTaskWithUrl:(NSURL *)url
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //设置请求超时时间
    self.sessionManager.requestSerializer.timeoutInterval = 60;
    
    NSURLSessionDownloadTask *downloadTask =  [self.sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        return [NSURL fileURLWithPath:RellayPath(_userInfor.UserID)];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error){
        if (![error.userInfo[@"NSLocalizedDescription"] isEqualToString:@"cancelled"])
        {
            if ([error.userInfo[@"NSLocalizedDescription"] isEqualToString:@"The request timed out."])
            {
                ZJLog(@"请求超时的url:%@", error.userInfo[@"NSErrorFailingURLKey"]);
                [self downloadTaskWithUrl:error.userInfo[@"NSErrorFailingURLKey"]];
                
            }
            else
            {
                ZJLog(@"\n%@", error.userInfo[@"NSLocalizedDescription"]);
                
                count++;
                
                float progress = (float)(count) / downCount * 100;
                
                ZJLog(@"%f", progress);
                
                if (progress < 99)
                {
                    self.downProgressLabel.text = [NSString stringWithFormat:@"%2.0f%%", progress];
                }
                else
                {
                    self.downProgressLabel.text = @"99%";
                }
                
                if (count == downCount)
                {
                    self.downProgressLabel.text = @"100%";
                    [self changeStatus:Completion];
                }
            }
            
        }
        
    }];
    [downloadTask resume];
}



版权声明:本文为xuanai_xue123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。