15

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.

James Zaghini
  • 3,895
  • 4
  • 45
  • 61
user3069232
  • 8,587
  • 7
  • 46
  • 87

1 Answers1

21

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
}
Community
  • 1
  • 1
James Zaghini
  • 3,895
  • 4
  • 45
  • 61
  • 1
    Thanks James, this kinda works only I need to add a / between resourcePath + imgName, and I end up with a filePath to the main bundle only, so not usable to access the assets.xcassets dog.png image. – user3069232 Dec 24 '15 at 05:50
  • Hey @user3069232, Ugh... forgot the forward slash! I've updated the code, see my edit. – James Zaghini Dec 24 '15 at 05:54
  • 27
    I would guess the down vote was because it doesn't answer the question as specified. This will not provide access to an image file stored in an xcassets. Such images are compiled into a file called Assets.car and so are not directly accessible via a pathname. – David Knight Feb 22 '17 at 21:30