Load image from iOS 8 framework

UIImage(named: "Background.png") calls NSBundle.mainBundle() in the internals. So, your code is trying to find resource in your host app's bundle, not in the frameworks bundle. To load UIImage from your framework's bundle use this snippet:

let frameworkBundle = NSBundle(forClass: YOURFRAMEWORKCLASS.self)
let imagePath = frameworkBundle.pathForResource("yourImage.png", ofType: "")
if imagePath != nil {
  result = UIImage(contentsOfFile: imagePath!)
}

Edited: added explanation (thx to milz)


In Swift 3.0:

let currentBundle = Bundle(for: YOURCLASS.self)
guard let path = currentBundle.path(forResource: imageName, ofType: "jpg") else {  return defaultImage }
return UIImage(contentsOfFile: path) ?? defaultImage

While @Renatus answer is perfectly valid and addresses the core issue (bundle for framework needs to be specified), I wanted to post the solution I went with since it's slightly more direct:

Swift 3.0/4.0/5.0

let image = UIImage(named: "YourImage", in: Bundle(for: YOURFRAMEWORKCLASS.self), compatibleWith: nil)

Alternatively, you can use this pattern for non-class, aka non-"static", functions:

let image = UIImage(named: "YourImage", in: Bundle(for: type(of: self)), compatibleWith: nil)

or this pattern for class functions:

let image = UIImage(named: "YourImage", in: Bundle(for: self), compatibleWith: nil)

These alternatives are better for cutting and pasting.


Another option is assigning the bundle identifier, which makes more sense than assigning class when it comes to readability.

In Swift 3:

UIImage(named: "MyImage", in: Bundle(identifier: "bundleIdentifier"), compatibleWith: nil)

Tags:

Swift

Ios8