14

Everything I google turns up answers about ALAsset's.

I have an images.xcassets folder and a bunch of assets in there.

I want to know if an asset exists in there based on a string.

E.g. if(images.xcassets.contains("assetName") == true)

Do you know how I can check if an asset exists based on a string?

Aggressor
  • 12,511
  • 18
  • 88
  • 165
  • I'm not sure on how to do this specifically, but I would just create an UIImage with the resource image name you are checking and if the UIImage is nil then you know that resource is not available and can try another. – SierraMike Feb 27 '15 at 21:26

5 Answers5

16

This is one way to check it.

NSString *someString = @"SomeStringFromSomwhere";

 if ([UIImage imageNamed: someString])
 { 
    //the image exists..
 } 
 else
 {
    //no image with that name
 }
Earl Grey
  • 7,129
  • 5
  • 35
  • 57
15

Just a bit more practical answer: Swift

if let myImage = UIImage(named: "assetName") {
  // use your image (myImage), it exists!
}
budiDino
  • 10,932
  • 8
  • 84
  • 83
13

Check whether image exist or not : Swift 3

if (UIImage(named: "your_Image_name") != nil) {
  print("Image existing")
}
else {
  print("Image is not existing")
}
Ram Madhavan
  • 2,166
  • 1
  • 15
  • 20
0

I ended up with some combination of both and turned it into a function to use throughout my code. I also want to return a default image if the one provided is missing. (Swift 4 version)

func loadImage (named: String) -> UIImage {

    if let confirmedImage = UIImage(named: named) {
        return confirmedImage
    } else {
        return UIImage(named: "Default_Image.png")
    }

}

Then to load the image into something like a button you do something like this.

buttonOne.setImage(loadImage(named: "YourImage.png"), for: .normal)
Dave Levy
  • 754
  • 10
  • 16
0

For Swift, this is what I ended up using to assign either an existing asset or a default system image:

myImageView.image = UIImage(named: "myAssetName") ?? UIImage(systemName: "photo")
// When former is nil, assigns default system image called "photo"
Cloud
  • 674
  • 1
  • 3
  • 17