Brandon Hardy Brandon Hardy - 1 year ago 171
iOS Question

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!)

Answer Source

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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download