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"
}
}
}
Related
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
}
I've got a struct, which contains a static variable called userProfileImage, this struct is in a view controller called UserProfilePage.swift, here is the code:
struct UserProfile {
static let userProfileImage = UIImageView(image: #imageLiteral(resourceName: "profilePicture"))
}
class UserProfilePage: UIViewController {
// Some code that sets the userProfileImage to another image
}
The following code is in another swift file that has a struct called Downloads:
struct Downloads {
guard let profilePicURL = URL(string: profilePictureString) else {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
print("Profile picture set to default profile picture")
return
}
// Some code
}
When profilePicURL is not empty, some code gets executed, but when it is empty (equal to ""), the code inside the else block gets executed. The problem is that the profile picture doesn't change, it just executes the print statement inside the else block. Does anyone know what's wrong with my code?
First of all, you have to change your userProfileImage. This Should be a var instead of **static let.
You can use if let statement with an async call in your code. Please try the following code.
let profilePictureString = "http://SOME URl STRING.."
if let profilePicURL = URL(string: profilePictureString){
// Plcae Your Network Code Here.
} else {
DispatchQueue.main.async {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
print("Profile picture set to default profile picture")
}
}
You can call the setNeedsDisplay() for update the imageview
DispatchQueue.main.async {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
UserProfile.userProfileImage.setNeedsDisplay()
}
use image literal
struct Downloads {
guard let profilePicURL = URL(string: profilePictureString) else {
UserProfile.userProfileImage.image = imageLiteral(resourceName: "profilePicture")
print("Profile picture set to default profile picture")
return
}
// Some code
}
I have 2 UIImageViews connected to an array of images
I'm trying compare both once they are displayed but doesn't seems to work.
I tried using imageArray[Image Literal] and also imageArray[image1.png, image2.png, image3.png, image4.png, image5.png]
I'm not sure what im doing wrong.
im not looking for the code although it may help but what im looking is for a someone to guide me to the right direction
#IBOutlet weak var 1ImageView: UIImageView!
#IBOutlet weak var 2ImageView: UIImageView!
let imageArray = [image1.png, image2.png, image3.png, image4.png, image5.png]
func any() {
if (1ImageView != nil) && (2ImageView != nil) && isEqual(image1.png) {
print("match!")
} else if ...// more if statements
…last if statement} else {
print(“no match!”)
}
#IBAction func buttonPressed(_ sender: IUButton) {
any()
}
If this is not possible is there a way to assign an identifier to each of the images inside the array..
sorry for the extra question.
there is one answer on comparing 2 images using NSData but Im not sure how to implement it to an array.
thanks and sorry but the newbie question.
image.isEqual(image) seems to be unreliable, despite what documentation says. If you don't need to make a pixel perfect comparison, converting image to a data and comparing those would be sufficient.
let image1 = UIImage(named: "image1.png")
let image2 = UIImage(named: "image2.png")
let imageData1 = image1?.pngData()
let imageData2 = image2?.pngData()
if imageData1 == imageData2 {
print("images are the same")
} else {
print("images are different")
}
Looking for a specific image inside an array can build on that:
// array of images referencing image files within an Xcode project
// it's not the best idea to force unwrap those, but for the sake of simplicity
let imageArray = [UIImage(named: "image1.png")!,
UIImage(named: "image2.png")!,
UIImage(named: "image3.png")!,
UIImage(named: "image4.png")!,
UIImage(named: "image5.png")!]
func anySimilarImages() {
// find first image which is the same as 1ImageView's
let 1ImageViewImage: UIImage? = imageArray.first { (image) -> Bool in
return image.pngData() == 1ImageView.image?.pngData()
}
// find first image which is the same as 2ImageView's
let 1ImageViewImage: UIImage? = imageArray.first { (image) -> Bool in
return image.pngData() == 2ImageView.image?.pngData()
}
if 1ImageViewImage != nil && 2ImageViewImage != nil {
print("both images were found")
}
else if 1ImageViewImage != nil {
print("first image was found")
}
else if 2ImageViewImage != nil {
print("second image was found")
}
else {
print("no image was found")
}
}
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"
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")
}