1

My question is about getting the filename of image of the UIImage that is used in a UIImageView.

Here is my sample code:

// Using image from UIImageObject
imageView1.image = myUIImage
// Using image from XAssets
imageView2.image = UIImage(named: "myImageName")

In UI Tests, how can I get the name of the image file? The expected resoult would be:

"myUImageObject" // For imageView1 
"myImageName" // For imageView2

Is there any way to get this value?

Thanks everyone!

  • Possible duplicate of https://stackoverflow.com/questions/1740274/uiimageview-how-to-get-the-file-name-of-the-image-assigned. – Martin R May 23 '17 at 09:58

3 Answers3

7

Unfortunately you can't do that, however there's an easy workaround, try something like this:

let myImageView = UIImageView()
myImageView.image = UIImage(named: "anyImage")
myImageView.restorationIdentifier = "anyImage" // Same name as image's name!

// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "anyImage"

Basically in this solution you're using the restoration identifier to hold the image's name, so you can use it later anywhere. If you update the image, you must also update the restoration identifier, like this:

myImageView.restorationIdentifier = "newImageName"

I hope that helps you, good luck!

ThiagoAM
  • 1,432
  • 13
  • 20
1

Swift 4

Declare Outlet

@IBOutlet weak var m_SetName_Img: UIImageView! //Image is already set image from Assets File

Declare Function

extension UIImageView {
    
    func getImageName() -> String {
        
        if let image = self.image, let imageName = image.accessibilityIdentifier {
            return imageName
        } else {
            return "nil"
        }
        
    }
    
}

Use

print(self.m_SetName_Img.getImageName())
1

You can use:

imageView2.image?.imageAsset?.value(forKey: "assetName")

assetName is private API, so officially out of bounds for the App Store, but for testing it should be just fine.

amadour
  • 1,600
  • 11
  • 20