Download file with AF.
download
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLSessionDownloadTask *task =[[AFHTTPSessionManager manager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"%@",downloadProgress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString *filePath = [NSString stringWithFormat:@"%@/%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0],response.suggestedFilename];
NSLog(@"%@",filePath);
return [NSURL fileURLWithPath:filePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
}];
[task resume];
By the way
NSString *homePath = NSHomeDirectory();
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSString *applicationSupportPath = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject;
NSString *preferencePath = NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSUserDomainMask, YES).firstObject;
NSString *temPath = NSTemporaryDirectory();
note
- destination path
return destination path的时候一定要注意return [NSURL fileURLWithPath:filePath]; 而不是 return [NSURL URLWithString:filePath];。
如果使用URLWithString,这样指定的文件路径是无效的,下载保存不了任何东西。
切勿搞混
[NSURL fileURLWithPath:filePath];
[NSURL URLWithString:filePath];
- 文件重命名
- 使用默认文件名称
NSString *filePath = [NSString stringWithFormat:@"%@/%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0],response.suggestedFilename];
return [NSURL fileURLWithPath:filePath];
- 重命名
NSString *filePath = [NSString stringWithFormat:@"%@/%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0],文件名.文件类型];
return [NSURL fileURLWithPath:filePath];
如果要重命名的话需要指定文件名和文件类型,没有文件类型,也能下载下来,但是可能用的时候会不方便。