High-Res UIImage remote load

Mon, 08. Nov 2010

Categories: en development Tags: Cocoa Image iPhone iPhone4 Retina Display UIImage

Loading UIImages automatically in high-resolution works fine for locally stored images โ€“ but if you want to fetch them via remote URL you have to code yourself.

A simple, blocking but backward compatible (iOS >= 3.0, maybe even 2.0 but untested) ย implementation could look like this:

 1@implementation UIImage (MRORemote)
 2
 3// add the @2x filename suffix
 4+(NSURL *)url2x:(NSURL *)url
 5{
 6  NSString *path = url.path;
 7  NSAssert(path != nil, @"");
 8  NSString *last = path.lastPathComponent;
 9  NSString *ext = path.pathExtension;
10  NSAssert(last != nil, @"");
11  NSAssert(ext != nil, @"");
12  NSString *part = [last substringToIndex:MAX(0, last.length - ext.length - 1)];
13  return [NSURL URLWithString:[NSString stringWithFormat:@"%@@2x.%@", part, ext] relativeToURL:[url absoluteURL]];
14}
15
16+(UIImage *)imageWithContentsOfURL:(NSURL *)url probe2x:(BOOL)probe2x
17{
18  if ( url == nil )
19    return nil;
20  UIScreen *screen = [UIScreen mainScreen];
21  const CGFloat scale = [screen respondsToSelector:@selector(scale)] ? [screen scale] : 1.0f;
22  if ( probe2x && 2.0f == scale && [UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)] ) {
23    UIImage *img = nil;
24    NSData *raw = [NSData dataWithContentsOfURL:[UIImage url2x:url]];
25    if ( raw != nil )
26      img = [UIImage imageWithData:raw];
27    if ( img != nil )
28      img = [UIImage imageWithCGImage:img.CGImage scale:scale orientation:img.imageOrientation];
29    if ( img != nil )
30      return img;
31    NSAssert(raw == nil && img == nil, @"");
32  }
33  // MRLogD(@"loading %@", [url absoluteURL]);
34  NSData *raw = [NSData dataWithContentsOfURL:url];
35  if ( raw == nil )
36    return nil;
37  return [UIImage imageWithData:raw];
38}
39@end

Use at your will but without any warranty.