NSURLSessionDownloadTask 下载文件

 -(void)RequestdataUI:(NSString*)ImageURL
imageName:(NSString*)imageName{ NSURL *url = [NSURL URLWithString:ImageURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//创建对象的同时 后台会开启一个新的线程去发出请求了
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *DownloadTask = [session downloadTaskWithRequest:request
completionHandler:^(NSURL *location, NSURLResponse *response,NSError *error) {
// 输出下载文件原来的存放目录
NSLog(@"%@", location); // 设置文件的存放目标路径
NSString *documentsPath = [self getDocumentsPath];
NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL]lastPathComponent]]; // 如果该路径下文件已经存在,就要先将其移除,在移动文件
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
[fileManager removeItemAtURL:fileURL error:NULL];
}
[fileManager moveItemAtURL:location toURL:fileURL error:NULL]; //--------创建plist文件-----------
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"imagePath.plist"];
NSMutableDictionary *PathPlist= [[[NSMutableDictionary alloc]initWithContentsOfFile:plistPath]mutableCopy];
if (PathPlist==nil) {
PathPlist = [[NSMutableDictionary alloc ] init];
}
[PathPlist setObject:imageName forKey:ImageURL];
[PathPlist writeToFile:plistPath atomically:YES ]; }]; [DownloadTask resume]; } - (NSString *)getDocumentsPath {
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = documents[];
NSString* ImagePath =[documentsPath stringByAppendingPathComponent:@"DownloadImage"];
//文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//新建文件夹
[fileManager createDirectoryAtPath:ImagePath withIntermediateDirectories:YES attributes:nil error:nil]; return ImagePath; }
上一篇:第7章 数据库访问与ORM 慕课网微信小程序开发学习笔记


下一篇:NGUI OnChange Event