美文网首页
ios 下载文件

ios 下载文件

作者: 指尖的跳动 | 来源:发表于2017-08-28 11:54 被阅读318次

    /**

    *  下载文件

    *

    *  @param path    url路径

    *  @param success  下载成功

    *  @param failure  下载失败

    *  @param progress 下载进度

    */

    + (void)downloadWithPath:(NSString *)path

    success:(HttpSuccessBlock)success

    failure:(HttpFailureBlock)failure

    progress:(HttpDownloadProgressBlock)progress;

    + (void)downloadWithPath:(NSString *)path

    success:(HttpSuccessBlock)success

    failure:(HttpFailureBlock)failure

    progress:(HttpDownloadProgressBlock)progress {

    //获取完整的url路径

    NSString * urlString = [kBaseUrl stringByAppendingPathComponent:path];

    //下载

    NSURL *URL = [NSURL URLWithString:urlString];

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSURLSessionDownloadTask *downloadTask = [[AFHttpClient sharedClient] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

    progress(downloadProgress.fractionCompleted);

    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

    //获取沙盒cache路径

    NSURL * documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

    if (error) {

    failure(error);

    } else {

    success(filePath.path);

    }

    }];

    [downloadTask resume];

    }

    相关文章

      网友评论

          本文标题:ios 下载文件

          本文链接:https://www.haomeiwen.com/subject/sfnwdxtx.html