Skip to content

Instantly share code, notes, and snippets.

@ryanmaxwell
Last active December 21, 2015 01:28
Show Gist options
  • Save ryanmaxwell/6227531 to your computer and use it in GitHub Desktop.
Save ryanmaxwell/6227531 to your computer and use it in GitHub Desktop.
Useful utility method to get the most appropriate image resource from the main bundle for the device based on filename. Fills a need until the new asset packages in Xcode 5 is released.
+ (UIImage *)imageResource:(NSString *)name ofType:(NSString *)type {
NSString *systemVersion = UIDevice.currentDevice.systemVersion;
NSString *iOSMajorSystemVersion = (systemVersion.length) ? [NSString stringWithFormat:@"iOS%@", [systemVersion substringToIndex:1]] : @"iOS";
if (UIScreen.mainScreen.bounds.size.height == 568.0f) {
/* iPhone 5 */
NSString *iPhone5SystemVersionImageName = [NSString stringWithFormat:@"%@-%@-568h@2x", name, iOSMajorSystemVersion];
NSString *iPhone5SystemVersionImagePath = [NSBundle.mainBundle pathForResource:iPhone5SystemVersionImageName ofType:type];
if ([NSFileManager.defaultManager fileExistsAtPath:iPhone5SystemVersionImagePath])
return [UIImage imageWithContentsOfFile:iPhone5SystemVersionImagePath];
NSString *iPhone5ImageName = [NSString stringWithFormat:@"%@-568h@2x", name];
NSString *iPhone5ImagePath = [NSBundle.mainBundle pathForResource:iPhone5ImageName ofType:type];
if ([NSFileManager.defaultManager fileExistsAtPath:iPhone5ImagePath])
return [UIImage imageWithContentsOfFile:iPhone5ImagePath];
}
if (UIScreen.mainScreen.scale == 2.0) {
/* Retina */
NSString *retinaSystemVersionImageName = [NSString stringWithFormat:@"%@-%@@2x", name, iOSMajorSystemVersion];
NSString *retinaSystemVersionImagePath = [NSBundle.mainBundle pathForResource:retinaSystemVersionImageName ofType:type];
if ([NSFileManager.defaultManager fileExistsAtPath:retinaSystemVersionImagePath])
return [UIImage imageWithContentsOfFile:retinaSystemVersionImagePath];
NSString *retinaImageName = [NSString stringWithFormat:@"%@@2x", name];
NSString *retinaImagePath = [NSBundle.mainBundle pathForResource:retinaImageName ofType:type];
if ([NSFileManager.defaultManager fileExistsAtPath:retinaImagePath])
return [UIImage imageWithContentsOfFile:retinaImagePath];
}
NSString *standardSystemVersionImageName = [NSString stringWithFormat:@"%@-%@", name, iOSMajorSystemVersion];
NSString *standardSystemVersionImagePath = [NSBundle.mainBundle pathForResource:standardSystemVersionImageName ofType:type];
if ([NSFileManager.defaultManager fileExistsAtPath:standardSystemVersionImagePath])
return [UIImage imageWithContentsOfFile:standardSystemVersionImagePath];
NSString *standardImagePath = [NSBundle.mainBundle pathForResource:name ofType:type];
if ([NSFileManager.defaultManager fileExistsAtPath:standardImagePath])
return [UIImage imageWithContentsOfFile:standardImagePath];
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment