所以我已经完成了关于SO的几乎所有问题,并且我已将它们全部放在一起创建一个接受两个参数的方法,首先是要在{{1中下载和显示的图像的URL
第二个是UIImageView
的占位符图像。我想保存图像,以便每次都不会下载。我使用SDWebImage下载图像,但是当使用SDWebImage将图像保存在文档目录中时我有些困惑,所以我决定不使用它。我使用UIImageView
,我的方法现在看起来像:
dispatch_sync(dispatch_get_main_queue()
我有几个问题,这个实现是否足够好,因为我正在开发应用程序商店的应用程序?从URL下载图像是否会异步完成? (我知道我正在使用- (void)saveImageFromURL:(UIImage*)image:(NSURL*)imageURL {
NSString *url = [imageURL absoluteString];
NSArray *parts = [url componentsSeparatedByString:@"/"];
NSString *filename = [parts lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", filename]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath];
if (fileExists) {
NSLog(@"File already exists");
_myUIImage.image = [UIImage imageNamed:fullPath];
return;
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.myUIImage sd_setImageWithURL:imageURL placeholderImage:image];
UIImage *imageFromURL = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
NSData *imageDataNew = UIImagePNGRepresentation(imageFromURL);
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:fullPath contents:imageDataNew attributes:nil];
});
}
}
,但只需要确认)。如果是,那么这不会阻止我的用户界面,对吗?
答案 0 :(得分:0)
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
// *** Load Image from URL Asynchronously without blocking Main thread ***
UIImage *imageFromURL = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
dispatch_async(dispatch_get_main_queue(), ^(void){
// *** Create file path to DocumentDirectory ***
NSString * docDirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [docDirPath stringByAppendingPathComponent:@"myImage.jpg"]
// *** Write Image to disk ***
BOOL isSaved = [UIImageJPEGRepresentation(image, 1.0f) writeToFile:dirPath atomically:YES];
if(isSaved)
{
NSLog(@"Image write to disc successfully.");
}
});
});