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 }