Loading images in background to optimize the loading in ios

后端 未结 9 1257
星月不相逢
星月不相逢 2021-02-02 03:02

I am trying to optimize the load in my application, in fact, I have a lot of images that loaded in my application, and I spend a lot of time waiting for a view controller to ope

9条回答
  •  悲哀的现实
    2021-02-02 03:48

    You can use async imageview.

    - (void) loadImageFromURL:(NSURL*)url placeholderImage:(UIImage*)placeholder cachingKey:(NSString*)key {
        self.imageURL = url;
        self.image = placeholder;
    
        NSData *cachedData = [FTWCache objectForKey:key];
        if (cachedData) {   
           self.imageURL   = nil;
           self.image      = [UIImage imageWithData:cachedData];
           return;
        }
    
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{
            NSData *data = [NSData dataWithContentsOfURL:url];
    
            UIImage *imageFromData = [UIImage imageWithData:data];
    
            [FTWCache setObject:data forKey:key];
    
            if (imageFromData) {
                if ([self.imageURL.absoluteString isEqualToString:url.absoluteString]) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        self.image = imageFromData;
                    });
                } else {
    //              NSLog(@"urls are not the same, bailing out!");
                }
            }
            self.imageURL = nil;
        });
    }
    

    Take a look at this link.You will have an idea on using async imageview.

提交回复
热议问题