Check if string name matches an asset in images.xcassets - ios

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?

This is one way to check it.
NSString *someString = #"SomeStringFromSomwhere";
if ([UIImage imageNamed: someString])
{
//the image exists..
}
else
{
//no image with that name
}

Just a bit more practical answer: Swift
if let myImage = UIImage(named: "assetName") {
// use your image (myImage), it exists!
}

Check whether image exist or not : Swift 3
if (UIImage(named: "your_Image_name") != nil) {
print("Image existing")
}
else {
print("Image is not existing")
}

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)

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"

Related

Swift: UIButton.currentImage is not working comparing image name

I'm trying to check the image name in the UIButton like this:
#IBAction func buttonTapped(_ sender: Any) {
if xcodeButton.currentImage == UIImage(named: "xcode") {
print("xcode image")
}
}
But I have a break point in the if statement and this is the output:
po xcodeButton.currentImage
▿ Optional<UIImage>
- some : <UIImage:0x6000011a93b0 named(main: xcode) {500, 500}>
but if I compare it
po xcodeButton.currentImage == UIImage(named: "xcode")
false
Any of you knows why the comparison is returning false? or how can compare the name of the image in UIButton?
I'll really appreciate your help.
You should use isEqual(_:) From Docs scroll to Comparing Images section
let image1 = UIImage(named: "MyImage")
let image2 = UIImage(named: "MyImage")
if image1 != nil && image1!.isEqual(image2) {
// Correct. This technique compares the image data correctly.
}
if image1 == image2 {
// Incorrect! Direct object comparisons may not work.
}
None of these solutions were working for me. So I used pngData to compare images:
let image1Data = UIImage(named: "MyImage")?.pngData()
let image2Data = UIImage(named: "MyImage")?.pngData()
if image1Data == image2Data {
// It compares data correctly
}

SwiftUI - Check If Image Exist

I am attempting to execute code if an image exist.
The issue is I am unable to capture the state of empty image call.
The result is I get an empty image, but would rather put a placeholder image if possible.
func procImage(inName: String) {
switch (inName) {
case inName:
imageName = inName.lowercased()
default:
imageName = "blank"
}
}
This check is easy but you need to be sure that default image always exists.
func getSafeImage(named: String) -> Image {
let uiImage = (UIImage(named: named) ?? UIImage(named: "Default.png"))!
return Image(uiImage: uiImage)
}
Try this code:
func procImage(inName: String) -> UIImage {
if let confirmedImage = UIImage(named: inName) {
return confirmedImage
} else {
return UIImage(named: "Default_Image.png")!
}
}
Thanks all for contributing.
The solutions on offer did not quite work in my case except for Moreno's solution, but offered a path to my solution.
I did not need to store the result of the check, but just validate the existence of the file.
So this is what I came up with which worked.
This may not be the optimal solution, so improved code will be welcomed.
func procImage(inName: String) {
let imageConvertToLowercase = inName.lowercased()
if getMember.firstName.lowercased() == imageConvertToLowercase {
if (UIImage(named: imageConvertToLowercase) != nil) {
imageName = imageConvertToLowercase
} else {
imageName = "blank"
}
}
}

Display image on button if the image exists

I am working on a image quiz. I have a button that will display either the correct image or the wrong image if there is no correct image. The unique question number comes from an array.
if (questionlist[1]correct = [UIImage imageNamed:#"questionlist[1]correct.png"]) {
Answer4.setImage(UIImage(named: "\(questionlist[1])correct.png"), forState: UIControlState.Normal)
} else {
Answer4.setImage(UIImage(named: "\(questionlist[1])fourthwrong.png"), forState: UIControlState.Normal)
}
Okay so if I'm understanding your questionList array is simply an array of numbers? So questionList = [1,2,3,etc]? In that case, you may want to try something like:
let imageName = "\(questionList[1])wrong.png" //for instance 2wrong.png
if (UIImage(named: imageName) == nil) { // no wrong image exists
imageView.image = UIImage(named: "\(questionList[1])correct.png")
} else {
imageView.image = UIImage(named: "\(questionList[1])wrong.png")
}
Of course this is assuming a correct image exists. It's unclear what you're after, some more information/more code would help.

check image in UIImageView is not a placeholder image and append to UIImage array

I have set a placeholder image for my image views. The user can change these to a photo from their library. Once they have done this, they can then upload these images to a database. The user can upload a single image or many, either way, they are uploaded as an [UIImage]. However, I do not want the placeholder images to be uploaded.
I have managed to achieve this, but in a very ungraceful manner. I have done this by firstly subclassing UIImageView, adding a property called isSet and setting all my image views to this class:
class ItemImageViewClass: UIImageView {
//keeps track of whether the image has changed from the placeholder image.
var isSet = Bool()
}
and then when the image has been set after the user has selected an image, the isSet property is set to true.
To check if the image in the image view has been changed from the placeholder image (i.e. isSet == true) I used the following code:
var imageArray: [UIImage]? = nil
if imageViewOne.isSet {
guard let mainImage = imageViewOne.image else {return}
if (imageArray?.append(mainImage)) == nil {
imageArray = [mainImage]
}
}
if imageViewTwo.isSet {
guard let imageTwo = imageViewTwo.image else {return}
if (imageArray?.append(imageTwo)) == nil {
imageArray = [imageTwo]
}
}
guard imageArray != nil else {
print("imageArray is nil")
alertMessage("Hey!", message: "Please add some images!")
return
}
When at least one image has been selected, the array will be saved to the database.
This seems like a very messy way to do it; subclassing UIImageView and having to check that each image has changed using a series of if statements. Is there a more elegant way to achieve this? Thanks
There is a solution by extending UIImageView to avoid subclassing. And, using filter and flatMap to by pass the if-statements. This requires that you use the same reference to the placeholder image for each UIImageView.
// In this example, the placeholder image is global but it doesn't have to be.
let placeHolderImage = UIImage()
extension UIImageView {
// Check to see if the image is the same as our placeholder
func isPlaceholderImage(_ placeHolderImage: UIImage = placeHolderImage) -> Bool {
return image == placeHolderImage
}
}
Usage:
let imageViewOne = UIImageView(image: placeHolderImage)
imageViewOne.isPlaceholderImage() // true
let imageViewTwo = UIImageView()
imageViewTwo.isPlaceholderImage() // false
let imageViewThree = UIImageView()
imageViewThree.image = UIImage(named: "my-image")
imageViewThree.isPlaceholderImage() // false
Filter and map for images that are not placeholders or nil:
let imageArray = [imageViewOne, imageViewTwo, imageViewThree].filter
{ !$0.isPlaceholderImage() }.flatMap { $0.image }
print(imageArray) // imageViewThree.image
If the extension does not work for your requirements, I would definitely consider "filter and flatMap" to avoid that if-statement.
I would recommend creating a new UI component for your needs with a background UIImageView(placeholder) and an optional foreground UIImageView (user selected). Then just check for the existence of the optional foreground UIImageView as you can rely upon this being the UIImageView containing the user chosen image.

UIImage on swift can't check for nil

I have the following code on Swift
var image = UIImage(contentsOfFile: filePath)
if image != nil {
return image
}
It used to work great, but now on Xcode Beta 6, this returns a warning
'UIImage' is not a subtype of 'NSString'
I don't know what to do, I tried different things like
if let image = UIImage(contentsOfFile: filePath) {
return image
}
But the error changes to:
Bound value in a conditional binding must be of Optional type
Is this a bug on Xcode6 beta 6 or am I doing something wrong?
Update
Swift now added the concept of failable initializers and UIImage is now one of them. The initializer returns an Optional so if the image cannot be created it will return nil.
Variables by default cannot be nil. That is why you are getting an error when trying to compare image to nil. You need to explicitly define your variable as optional:
let image: UIImage? = UIImage(contentsOfFile: filePath)
if image != nil {
return image!
}
The simplest way to check if an image has content (> nil) is:
if image.size.width != 0 { do someting}
func imageIsNullOrNot(imageName : UIImage)-> Bool
{
let size = CGSize(width: 0, height: 0)
if (imageName.size.width == size.width)
{
return false
}
else
{
return true
}
}
the Above method call Like as :
if (imageIsNullOrNot(selectedImage))
{
//image is not null
}
else
{
//image is null
}
here, i check image size.
Init, that you are call init?(contentsOfFile path: String) the ? means that it returns optional value.
You should check optional vars for nil before use it.
Shorter, than accepted answer and Swift-style way, than named Optional Chaining to do that:
if let image = UIImage(contentsOfFile: filePath) {
return image
}
You can check it's imageAsset like this:
if image.imageAsset != nil
{
// image is not null
}
else
{
//image is null
}
You can check for it's width, which would be 0 if no image is uploaded.
if(image.size.width != 0){
print("image found")
} else {
print("image is null")
}

Resources