How to handle NSData and return UIImage (Swift)

和自甴很熟 提交于 2019-12-06 00:28:57

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

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()
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!