iOS 开发-AFNetworking Block下载文件保存到沙盒

来源:互联网 发布:香港淘宝网电话 编辑:程序博客网 时间:2024/06/05 10:54

AFNetworking 2.X

 *  @author Jakey * *  @brief  下载文件 * *  @param parameters   附加post参数 *  @param requestURL 请求地址 *  @param savedPath  保存 在磁盘的位置 *  @param success    下载成功回调 *  @param failure    下载失败回调 *  @param progress   实时下载进度回调 */- (void)downloadFileWithOption:(NSDictionary *)parameters                 withInferface:(NSString*)requestURL                     savedPath:(NSString*)savedPath               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure                      progress:(void (^)(float progress))progress{    //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURL parameters:parameters error:nil];//以下是手动创建request方法 AFQueryStringFromParametersWithEncoding有时候会保存//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]];//   NSMutableURLRequest *request =[[[AFHTTPRequestOperationManager manager]requestSerializer]requestWithMethod:@"POST" URLString:requestURL parameters:paramaterDic error:nil];////    NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));//    //    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];//    [request setHTTPMethod:@"POST"];////    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(paramaterDic, NSASCIIStringEncoding) dataUsingEncoding:NSUTF8StringEncoding]];    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {        float p = (float)totalBytesRead / totalBytesExpectedToRead;        progress(p);        NSLog(@"download:%f", (float)totalBytesRead / totalBytesExpectedToRead);    }];    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {        success(operation,responseObject);        NSLog(@"下载成功");    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        success(operation,error);        NSLog(@"下载失败");    }];    [operation start];}
//使用- (IBAction)downloadTouched:(id)sender {    NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/QQ7.6.exe"];    //    NSDictionary *paramaterDic= @{@"jsonString":[@{@"userid":@"2332"} JSONString]?:@""};    [self downloadFileWithOption:@{@"userid":@"123123"}                   withInferface:@"http://dldir1.qq.com/qqfile/qq/QQ7.6/15742/QQ7.6.exe"                       savedPath:savedPath                 downloadSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {    } downloadFailure:^(AFHTTPRequestOperation *operation, NSError *error) {    } progress:^(float progress) {    }];}

AFNetworking 3.X

- (void)downloadFileWithURL:(NSString*)requestURLString                 parameters:(NSDictionary *)parameters                  savedPath:(NSString*)savedPath            downloadSuccess:(void (^)(NSURLResponse *response, NSURL *filePath))success            downloadFailure:(void (^)(NSError *error))failure           downloadProgress:(void (^)(NSProgress *downloadProgress))progress{    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURLString parameters:parameters error:nil];    NSURLSessionDownloadTask *task = [[AFHTTPSessionManager manager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {        progress(downloadProgress);    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {        return [NSURL fileURLWithPath:savedPath];    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {        if(error){            failure(error);        }else{            success(response,filePath);        }    }];    [task resume];}

调用

- (IBAction)downloadTouched:(id)sender {    NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/QQ7.6.exe"];   [self downloadFileWithURL:@"http://dldir1.qq.com/qqfile/qq/QQ7.6/15742/QQ7.6.exe" parameters:@{@"userid":@"123123"} savedPath:savedPath downloadSuccess:^(NSURLResponse *response, NSURL *filePath) {   } downloadFailure:^(NSError *error) {   } downloadProgress:^(NSProgress *downloadProgress) {      NSLog(@"总大小:%lld,当前大小:%lld",downloadProgress.totalUnitCount,downloadProgress.completedUnitCount);   }];}

问题
有些人的AFNetworking 3 progress参数是一个指针,并不是一个block,如下:

- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask                          progress:(NSProgress * __autoreleasing *)progress                        destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination                  completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler

可以自行更新到最新版本的AFN或者使用KVO监听progress,progress是一个NSProgress实例

NSProgress *progress;[manager downloadTaskWithRequest:request progress:&progress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {...
[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {        NSProgress *progress = (NSProgress *)object;       NSLog(@"总大小:%lld,当前大小:%lld",progress.totalUnitCount,progress.completedUnitCount);    }}
0 0