How to handle NSData and return UIImage (Swift)

2019-05-09 20:12发布

问题:

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

回答1:

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())
}


回答2:

You can download image from an URL and return as an UIImage with this code. Hope this helps:

func downloadImage(url: NSURL) -> UIImage {

        getDataFromUrl(url) { (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                guard let data = data where error == nil else { return }

                let image:UIImage = UIImage(data: data)!

                return image
            }
        }
    }

Update: this is the getDataFromUrl function

func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
        NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
            completion(data: data, response: response, error: error)
            }.resume()
    }