UIImage using contentsOfFile
If you need to use pathForResource() for avoiding image caching, it is not possible to work with images.xcassets. In that case you need to create group in XCode, and add image there (be sure, that image is copied to Copy Bundle Resources). Afterwards just write:
Swift 5:
let bundlePath = Bundle.main.path(forResource: "imageName", ofType: "jpg")
let image = UIImage(contentsOfFile: bundlePath!)
Older Swift:
let bundlePath = NSBundle.mainBundle().pathForResource("imageName", ofType: "jpg")
let image = UIImage(contentsOfFile: bundlePath!)
import Foundation
import UIKit
enum UIImageType: String {
case PNG = "png"
case JPG = "jpg"
case JPEG = "jpeg"
}
extension UIImage {
convenience init?(contentsOfFile name: String, ofType: UIImageType) {
guard let bundlePath = Bundle.main.path(forResource: name, ofType: ofType.rawValue) else {
return nil
}
self.init(contentsOfFile: bundlePath)!
}
}
Use:
let imageView.image = UIImage(contentsOfFile: "Background", ofType: .JPG)