我将图像作为NSData并将其保存到文档文件夹。
问题是,当我尝试保存文档文件夹时,它会保存4个中的2个,或者4个中的3个。它会随机保存。
我无法弄清楚问题出在哪里,因为在第一次保存失败后,第二次尝试可能会对特定图像成功。
你能帮我吗?
NSData * response = [appDel.serviceHelper serviceCall:@"" withURL:[NSString stringWithFormat:@"%@/Application/GetImage/%@",appDel.appPage.editorServiceURL,ID]];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/Images"];
if(response !=nil)
{
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
UIImage *image = [[UIImage alloc] initWithData:response];
NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@",dataPath,[NSString stringWithFormat:@"%@",fileName]];
NSData *data1;
if([pngFilePath rangeOfString:@".png"].location !=NSNotFound)
{
data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSLog(@"png Image");
}
else if([pngFilePath rangeOfString:@".jpg"].location !=NSNotFound)
{
data1 = [NSData dataWithData:UIImageJPEGRepresentation(image,1.0)];
NSLog(@"jpg Image");
}
else
{
NSLog(@"another extension Image");
}
[data1 writeToFile:pngFilePath atomically:YES];
//[appDel.fileHelper writeToFile:response withFileName:fileName];
}
答案 0 :(得分:0)
#define DocumentsPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
NSURLSession *defaultNSURLSession ;
CallMethod:
[self downloadImage_WithImageName:@"HERE YOUR FILENAME" FromFileURL:@"HERE IMAGE URL"];
-(void) downloadImage_WithImageName:(NSString *)imageName FromFileURL:(NSString *)fileURL{
NSString *dataPath = [DocumentsPath stringByAppendingPathComponent:@"/Images"];
NSString *filePath=[[NSString alloc] initWithFormat:@"%@/Images/%@",DocumentsPath,imageName];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
//NSLog(@"Downloading %@ to %@...", fileURL, filePath);
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:fileURL]];
NSURLSessionDownloadTask *downTask = [defaultNSURLSession downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
if (!error) {
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSError *err = nil;
if ([[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:&err]) {
//Reload your UITableview or UICollectionView
}else{
NSLog(@"move error %@", error);
}
}else{
NSLog(@"error %@",error);
}
}];
[downTask resume];
} else {
NSLog(@"%@ already exists. not downloading.", imageName);
}
}
答案 1 :(得分:0)
尝试将响应作为NSMutableDictionary而不是NSData。这可能会告诉你异常是什么。