UIImage using contentsOfFile UIImage using contentsOfFile xcode xcode

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 Foundationimport UIKitenum 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)


When you implement array of images from the images group resource,you can load each images(lets say b1,b2,b3,b4,b5) as

var imageIndex = 0lazy var imageList = ["b1","b2","b3","b4","b5"]let imagePath = Bundle.main.path(forResource: imageList[imageIndex], ofType: "jpg")imageview.image = UIImage(contentsOfFile: imagePath!)