消息关闭
    暂无新消息!
ios 中用afnetworking下载word文档然后存储到沙盒library(acche)目录下怎么做,求大神指点

1个回答

︿ 0
//下载
/*
 url:资源下载地址
 saveFilePath:下载完存储的地址
 */
+ (void)downloadFile:(NSString *)url
         andSaveFile:(NSString *)saveFilePath
      andFinishBlock:(void (^)(BOOL success))finishCallback
    andProgressBlock:(void (^)(long long totalBytesWritten, long long totalBytesExpectedToWrite))progressCallback {
    
    NSURL *url1 = [[NSURL alloc] initWithString:url];
    //默认配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //AFN3.0+基于封住URLSession的句柄
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLRequest *request = [NSURLRequest requestWithURL:url1];
    
    NSURLSessionDownloadTask *operation = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //打印下下载进度
        NSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        if (progressCallback) {
            progressCallback(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount,downloadProgress.totalUnitCount);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //下载地址
        NSLog(@"默认下载地址:%@",targetPath);
        
        //设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        return [NSURL URLWithString:filePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //下载完成后调用的方法
        NSLog(@"%@",response.URL);
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:saveFilePath]) {
            [fileManager createFileAtPath:saveFilePath contents:nil attributes:nil];
        }
        NSData * data = [NSData dataWithContentsOfURL:response.URL];
        if (data != nil) {
            [data writeToFile:saveFilePath atomically:NO];
        }
        
        if (finishCallback) {
            if (error == nil) {
                finishCallback(YES);
            }else{
                finishCallback(NO);
            }
            
        }
    }];
    [operation resume];
}