How to Speed Up Image Loading in iOS Apps: URL Fixing and Cache Optimization
This article analyzes why image loading can become a bottleneck in iOS apps like NetEase Cloud Music, identifies factors such as image size, network conditions, and cache behavior, and presents a comprehensive solution that standardizes URL parameters, reuses local images, and extends SDWebImage's manager and cache to achieve up to 50% faster downloads and significant CDN bandwidth savings.
Background
In many mobile apps, especially social‑heavy ones like NetEase Cloud Music, large numbers of images are displayed in feeds and galleries. When images are not delivered quickly, user experience suffers and retention drops, making image‑download optimization critical.
Existing Image‑Download Technique
The app currently uses a remote image service that supports on‑the‑fly cropping and quality compression via URL parameters.
Factors Affecting Image Download
Image size
Network conditions
Local cache
CDN cache
Optimization Approaches
Network Optimization
Switch from HTTP/1.0 to HTTP/2 to enable multiplexing and reduce connection overhead.
Limit bandwidth for audio/video streams that may otherwise dominate the network.
Image Size Optimization
Convert images to WebP by adding type=webp to the request.
On‑Demand Cropping and Quality Adjustment
Download only the size needed for the UI component (e.g., a 100×100 control on a 3× screen needs a 300×300 image).
Use lower quality (e.g., 80) when high fidelity is unnecessary.
Evidence Collection
Analysis of backend logs revealed three main issues:
Inconsistent URL parameters prevented cache hits, causing duplicate downloads and low CDN hit rates.
Device‑specific UI sizes led to many different cropping requests, increasing server‑side processing.
Quality parameters were set arbitrarily by upstream business logic, resulting in a wide range of image qualities.
Solution
1. URL Parameter Standardization
All image URLs are normalized by sorting parameters alphabetically, removing duplicates, and fitting size and quality into predefined tiers. Example URL before fixing:
http://path?imageView=1&enlarge=1&quality=80&thumbnail=80x80&type=webpThe fixing routine extracts NSURLQueryItem objects, applies size and quality tiering, removes duplicate keys, sorts them, and rebuilds the URL.
2. Local Image Reuse
When a requested image is not found in the cache, the system searches for a larger cached image that can be down‑scaled locally, avoiding a network request. The process involves:
Generating a cache key that strips the host and keeps only the query part.
Storing a WebImageCacheKeyAndURLObject that records the original URL path, cache key, image dimensions, and cropping mode.
When a cache miss occurs, searching the database for related objects that satisfy size, quality, and cropping constraints.
3. Extending SDWebImage
The standard SDWebImageManager is subclassed to apply the URL fix before delegating to the original loader. A new method loadImageWithURL:options:context:progress:completed: receives a corp flag indicating whether additional cropping is required.
- (SDWebImageCombidOperation *)loadImageWithURL:(NSURL *)url
options:(SDWebImageOptions)options
context:(SDWebImageContext *)context
progress:(SDImageLoaderProgressBlock)progressBlock
completed:(SDInternalCompletionBlock)completedBlock
corp:(BOOL)corp {
NSURL *fixURL = [self.class fixURLWithUrl:url];
SDInternalCompletionBlock fixBlock = completedBlock;
if (![fixURL.absoluteString isEqualToString:url.absoluteString] && corp) {
fixBlock = [self.class fixCompletedBlockWithOriginCompletedBlock:completedBlock url:url];
}
return [super loadImageWithURL:fixURL options:options context:context progress:progressBlock completed:^void(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (fixBlock) {
fixBlock(image, data, error, cacheType, finished, imageURL);
}
}];
}4. Cache Key Redesign
The cache key generation removes the host part of the URL, ensuring that different parameter orders map to the same key after the URL fix.
+ (NSString *)cacheKeyForURL:(NSURL *)url {
NSString *absoluteString = url.absoluteString;
NSString *host = url.host;
if (!host) return absoluteString;
NSRange hostRange = [absoluteString rangeOfString:host];
if (hostRange.location + hostRange.length < absoluteString.length) {
NSString *subString = [absoluteString substringFromIndex:hostRange.location + hostRange.length];
if (subString.length) return subString;
}
return absoluteString;
}5. Image Reuse Logic
The method canReuseObject evaluates cached images against the requested size, quality, and cropping mode, discarding animated images and ensuring the candidate image is at least as large and of equal or higher quality.
- (WebImageCacheKeyAndURLObject *)canReuseObject {
WebImageURLInfo *info = self.urlInfo;
if (CGSizeEqualToSize(CGSizeZero, info.requestSize)) return nil;
NSArray *candidates = [self relationObjects];
// filter non‑animated, size > 0
candidates = [candidates bk_select:^BOOL(WebImageCacheKeyAndURLObject *obj) {
return !obj.imageInfo.isAnimation && obj.imageInfo.size.width > 0 && obj.imageInfo.size.height > 0 && ![obj.cacheKey isEqualToString:self.cacheKey];
}];
// filter by quality
candidates = [candidates bk_select:^BOOL(WebImageCacheKeyAndURLObject *obj) {
NSInteger quality = obj.urlInfo.quality ?: 75;
NSInteger reqQuality = info.quality ?: 75;
return quality >= reqQuality;
}];
// further filter by cropping mode (x/z vs y) – omitted for brevity
return candidates.firstObject;
}Result
After integrating URL standardization, local image reuse, and the extended SDWebImage components, the team observed roughly a 30‑50% reduction in image‑download latency and at least a 10% daily reduction in CDN bandwidth consumption.
This article is originally from the NetEase Cloud Music technical team. Unauthorized reproduction is prohibited.
References
https://sf.163.com/help/documents/66982522786074624
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
