Load image from URL on WatchKit

fabian picture fabian · Apr 5, 2015 · Viewed 7.4k times · Source

Is there a more elegant solution to load an external image on the watch than the following ?

let image_url:String = "http://placehold.it/350x150"

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    let url:NSURL = NSURL(string:image_url)!
    var data:NSData = NSData(contentsOfURL: url)!
    var placeholder = UIImage(data: data)!

    // update ui
    dispatch_async(dispatch_get_main_queue()) {
        self.imageView.setImage(placeholder)
    }
}

Answer

Fokke Zandbergen picture Fokke Zandbergen · Dec 1, 2015

NSURL is meant to be used for local files. Instead use NSURLSession. It's also useful to set the scale for the remote image.

import WatchKit

public extension WKInterfaceImage {

    public func setImageWithUrl(url:String, scale: CGFloat = 1.0) -> WKInterfaceImage? {

        NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { data, response, error in
            if (data != nil && error == nil) {
                let image = UIImage(data: data!, scale: scale)

                dispatch_async(dispatch_get_main_queue()) {
                    self.setImage(image)
                }
            }
        }.resume()

        return self
    }
}

Use it like this

self.imageView.setImageWithUrl(image_url, scale: 2.0)