Saving image from a URL asynchronously

时间:2021-10-14 09:02:03

So i have already gone through almost all questions on SO, and I have put them all together to create a method that accepts two paramaters, first is the URL of the image to download and display in UIImageView and second is the placeholder image for that UIImageView. I want to save the image so that it won't be downloaded every time. I have used SDWebImage to download the image, however i had some confusion when it came to saving the image in documents directory using SDWebImage, so i decided not to use it. I used dispatch_sync(dispatch_get_main_queue() and my method now looks like :

所以我已经完成了关于SO的几乎所有问题,并且我已将它们全部放在一起创建一个接受两个参数的方法,首先是要在UIImageView中下载和显示的图像的URL,其次是该UIImageView的占位符图像。我想保存图像,以便每次都不会下载。我使用SDWebImage下载图像,但是当使用SDWebImage将图像保存在文档目录中时我有些困惑,所以我决定不使用它。我使用了dispatch_sync(dispatch_get_main_queue(),我的方法现在看起来像:

- (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];
    });
  }
}

I have a couple of questions, is this implementation good enough since i am working on a app that will be on app store ? Will the downloading of the image from URL be done asynchronously ? (i know i am using dispatch_async but just need to confirm). If yes, then this wont block my UI, right ?

我有几个问题,这个实现是否足够好,因为我正在开发应用程序商店的应用程序?从URL下载图像是否会异步完成? (我知道我正在使用dispatch_async,但只需要确认)。如果是,那么这不会阻止我的UI,对吧?

1 个解决方案

#1


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.");
        }
    });
});

#1


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.");
        }
    });
});