AFN实现下载操作


- (void)download
{
    // 1.创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 2.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com/img/bd_logo1.png"]];

    //3.创建下载任务
    /*
     第一个参数:请求对象
     第二个参数:进度回调 downloadProgress(获得进度信息)
     第三个参数:destination
                targetPath:文件的临时存储路径
                response:响应头信息
                返回值:NSURL(AFN内部已经实现了文件剪切的过程,但是需要我们告诉他应该把文件剪切到哪里)
     第四个参数:completionHandler 请求完成的时候调用
                response:响应头信息
                filePath==fullPath 文件的最终目录
                error:错误信息
     */
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount /downloadProgress.totalUnitCount);

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

        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

        NSLog(@"---%@---\n%@",targetPath, fullPath);

        //NSLog(@"%@--%@",[NSURL URLWithString:fullPath],[NSURL fileURLWithPath:fullPath]);
        return [NSURL fileURLWithPath:fullPath];

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

        NSLog(@"下载完成");
    }];

    //4.执行方法
    [downloadTask resume];
}


参考链接
参考链接
参考链接

你可能感兴趣的:(AFN实现下载操作)