Search code examples
iosswiftnsdatanserror

How to handle NSData and return UIImage (Swift)


I am trying to retrieve an image from a URL from a backendless database & convert this into an image, and return the function with a UIImageView. How do I handle a NSError in this code, and still return the UIImageView?

func getImage() -> UIView {

    let imageLink = backendless.userService.currentUser.getProperty("Avatar")

    let URL = NSURL(string: imageLink as! String)

    let data = NSData(contentsOfURL: URL!)

    let image: UIImage!

    image = UIImage(data: data!)

    return UIImageView(image: image!)
}

Solution

  • Updated my answer based on the comments.

    You can return a placeholder image if the one you are looking for is not available:

    So your method will look like the following:

    func getImage() -> UIImage {
    
        var imageLink = backendless.userService.currentUser.getProperty("Avatar")
    
        guard let imageUrl = imageLink as? String,
            let URL = NSURL(string: imageUrl),
            let data = NSData(contentsOfURL: URL)
             else {
                return UIImage(named: "placeholder")
        }
    
        return UIImage(data: data)
    }
    

    Here is how you use it:

    func koloda(koloda: KolodaView, viewForCardAtIndex index: UInt) -> UIView {
        return UIImageView(image: getImage())
    }