Search code examples
iosobjective-cswiftpathicloud

Figuring assets.xcassets path programmatically using SWIFT


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.


Solution

  • 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
    }