NSURLSessionDownloadTask 下载文件

 1 -(void)RequestdataUI:(NSString*)ImageURL
 2            imageName:(NSString*)imageName{
 3     
 4     NSURL *url = [NSURL URLWithString:ImageURL];
 5     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 6     //创建对象的同时 后台会开启一个新的线程去发出请求了
 7     NSURLSession *session = [NSURLSession sharedSession];
 8     NSURLSessionDownloadTask *DownloadTask = [session downloadTaskWithRequest:request
 9                                                             completionHandler:^(NSURL *location, NSURLResponse *response,NSError *error) {
10         // 输出下载文件原来的存放目录
11         NSLog(@"%@", location);
12         
13         // 设置文件的存放目标路径
14         NSString *documentsPath = [self getDocumentsPath];
15         NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
16         NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL]lastPathComponent]];
17      
18         // 如果该路径下文件已经存在,就要先将其移除,在移动文件
19         NSFileManager *fileManager = [NSFileManager defaultManager];
20         if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
21             [fileManager removeItemAtURL:fileURL error:NULL];
22         }
23         [fileManager moveItemAtURL:location toURL:fileURL error:NULL];
24 
25         //--------创建plist文件-----------
26         NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"imagePath.plist"];
27         NSMutableDictionary *PathPlist= [[[NSMutableDictionary alloc]initWithContentsOfFile:plistPath]mutableCopy];
28         if (PathPlist==nil) {
29             PathPlist = [[NSMutableDictionary alloc ] init];
30         }
31         [PathPlist setObject:imageName forKey:ImageURL];
32         [PathPlist writeToFile:plistPath atomically:YES ];
33         
34     }];
35     
36     [DownloadTask resume];
37    
38 
39 }
40 
41  
42 - (NSString *)getDocumentsPath {
43     NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
44     NSString *documentsPath = documents[0];
45     NSString* ImagePath =[documentsPath stringByAppendingPathComponent:@"DownloadImage"];
46     //文件管理器
47     NSFileManager *fileManager = [NSFileManager defaultManager];
48     //新建文件夹
49     [fileManager createDirectoryAtPath:ImagePath withIntermediateDirectories:YES attributes:nil error:nil];
50     
51     return ImagePath;
52  
53 }

 

转载于:https://www.cnblogs.com/Merrill/p/5112549.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值