IOS How do I asynchronously download and cache images and videos for use in my app

后端 未结 2 1701
离开以前
离开以前 2020-12-07 14:43

I have an iphone application that displays both images and videos. The way the app is structured most of the images and videos will remain the same, with one occasionally ad

2条回答
  •  天命终不由人
    2020-12-07 15:41

    It is very simple to download and cache. The following code will asynchronously download and cache.

    NSCache *memoryCache; //assume there is a memoryCache for images or videos
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    
        NSString *urlString = @"http://URL";
    
        NSData *downloadedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    
        if (downloadedData) {
    
            // STORE IN FILESYSTEM
            NSString* cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *file = [cachesDirectory stringByAppendingPathComponent:urlString];
            [downloadedData writeToFile:file atomically:YES];
    
            // STORE IN MEMORY
            [memoryCache setObject:downloadedData forKey:urlString];
        }
    
        // NOW YOU CAN CREATE AN AVASSET OR UIIMAGE FROM THE FILE OR DATA
    });
    

    Now there is something peculiar with UIImages that makes a library like SDWebImage so valuable , even though the asynchronously downloading images is so easy. When you display images, iOS uses a lazy image decompression scheme so there is a delay. This becomes jaggy scrolling if you put these images into tableView cells. The correct solution is to image decompress (or decode) in the background, then display the decompressed image in the main thread.

    To read more about lazy image decompression, see this: http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/

    My advice is to use SDWebImage for your images, and the code above for your videos.

提交回复
热议问题