aircraft aircraft - 4 days ago 6
iOS Question

How to check a image url is real exist - iOS?

In iOS, could I check a

url
if is a real image path?

such as:

1)http://www.imgs.ie/uploads/banners/esb1.png

this is a real
url
path of
image
, but how can I check it is exist in code ?

2)http://www.imgs.ie/uploads/banners/esb2.png

this is a fail
url
path of
image
, but how can I check it is not exist in code ?

EDIT

thanks for
rmaddy
's advice, and my requirement is do not download the
image
, just want to know the url if is a real image url, and just like a
probe
of the url. we can check that.

Answer

Why don't your try this:

var imageURL: NSURL? {
    didSet {
        image = nil
        if view.window != nil {
            fetchImage()
        }
    }
}

private func fetchImage() {
    if let url = imageURL {
        DispatchQueue.global(qos: .userInitiated).async {
            self.spinner?.startAnimating()
            let contentsOfURL = NSData(contentsOf: url as URL)
            DispatchQueue.main.async {
                if url == self.imageURL {
                    if let imageData = contentsOfURL {
                        self.image = UIImage(data: imageData as Data)
                    } else {
                        self.spinner?.stopAnimating()
                    }
                } else {
                    print("ignored data returned from url \(url)")
                }
            }
        }
    }
}

And when you want to use imageURL:

let ImageNames = ["esbn": "http://www.imgs.ie/uploads/banners/esb1.png"]

func getImageNamed(imageName: String?) -> NSURL? {
    if let urlstring = ImageNames[imageName ?? ""] {
        return NSURL(string: urlstring)
    } else {
        return nil
    }
}

imageURL = getImageNamed(imageName: imageName)
Comments