Check if string name matches an asset in images.xcassets
Asked Answered
S

5

18

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?

Stephanystephen answered 27/2, 2015 at 21:24 Comment(1)
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.Allout
W
20

This is one way to check it.

NSString *someString = @"SomeStringFromSomwhere";

 if ([UIImage imageNamed: someString])
 { 
    //the image exists..
 } 
 else
 {
    //no image with that name
 }
Weimer answered 27/2, 2015 at 21:27 Comment(0)
P
17

Just a bit more practical answer: Swift

if let myImage = UIImage(named: "assetName") {
  // use your image (myImage), it exists!
}
Pierce answered 5/10, 2017 at 13:25 Comment(0)
T
15

Check whether image exist or not : Swift 3

if (UIImage(named: "your_Image_name") != nil) {
  print("Image existing")
}
else {
  print("Image is not existing")
}
Teryn answered 7/9, 2017 at 10:43 Comment(0)
B
1

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"
Breakfast answered 17/5, 2020 at 12:40 Comment(0)
G
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)
Grainfield answered 19/7, 2018 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.