Load image asynchronously from file

I have a relatively image in local storage, I want to show it to the user without breaking the user interface stream. I am currently using

[[UIImage alloc] initWithContentsOfFile:path];

to upload an image.

Any suggestions / help please ....

+3
source share
2 answers

If all you are trying to do is maintain access to the user interface stream, set up a short method to load it in the background and update imageView when it is done:

-(void)backgroundLoadImageFromPath:(NSString*)path {
    UIImage *newImage = [UIImage imageWithContentsOfFile:path];
    [myImageView performSelectorOnMainThread:@selector(setImage:) withObject:newImage waitUntilDone:YES];
}

This assumes that it myImageViewis a member variable of the class. Now just run it in the background from any thread:

[self performSelectorInBackground:@selector(backgroundLoadImageFromPath:) withObject:path];

, backgroundLoadImageFromPath , setImage: , , setImage: .

+5

NSInvocationOperation:

NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                    initWithTarget:self
                                    selector:@selector(loadImage:)
                                    object:imagePath];
[queue addOperation:operation];

:

- (void)loadImage:(NSString *)path

{

NSData* imageFileData = [[NSData alloc] initWithContentsOfFile:path];
 UIImage* image = [[UIImage alloc] initWithData:imageFileData];

[self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
}

- (void)displayImage:(UIImage *)image
{
    [imageView setImage:image]; //UIImageView
}
0

Source: https://habr.com/ru/post/1770145/


All Articles