Figuring assets.xcassets path programmatically using SWIFT

user3069232 picture user3069232 · Dec 23, 2015 · Viewed 15k times · Source

Trying to figure the path to the images with swift code. I got this that I think works in objective C.

[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.png", [[NSBundle mainBundle] resourcePath], imgName]];

To get the path for my .png image I stored in assets.xcassets. But I need to do so in SWIFT now, not objective C.

I need the path cause I am trying to upload the image I put there to an CKAsset in iCloud.

Answer

James Zaghini picture James Zaghini · Dec 23, 2015

If you only need the path to the file (and not an instance of UIImage), this will do it:

Swift 2:

if let resourcePath = NSBundle.mainBundle().resourcePath {
    let imgName = "dog.png"
    let path = resourcePath + "/" + imgName
}

Swift 3/4:

if let resourcePath = Bundle.main.resourcePath {
    let imgName = "dog.png"
    let path = resourcePath + "/" + imgName
}