Load Image from Url on Watchkit

How to load image from URL on watchos 2?

Its no framwork, but I've written this extension:

extension WKInterfaceImage {
public func imageFromUrl(_ urlString: String) {

if let url = NSURL(string: urlString) {

let request = NSURLRequest(url: url as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let imageData = data as Data? {
DispatchQueue.main.async {
self.setImageData(imageData)
}
}
});

task.resume()
}
}
}

Just add a WKInterfaceImage to your watchOS storyboard, attach it and then call
imageView.imageFromUrl("https://something")

Let me know if it works!

image by url for Apple Watch

The URL string need to conform to URL format as described in RFC 2396 . Basically, you need to have http:// or ftp, etc. at the beginning of your URL string.

WatchKit Retrieve Multiple URL Images

Are you requesting both images from the same sendMessage call? There is a size limit for how large the NSData object can be, and it's only a few megabytes. You might want to try to break the requests to retrieve the images into two separate calls.

Also, is there any error message printed from your error handler?

WatchKit not download picture

I had a similar issue just to download an image to the watch with NSData, but I didn't transfer it from the iPhone. The image also was not displayed on the real watch, but in the simulator.

I just switched to NSUrlSession.dataTaskWithURL and it worked:

        func loadImage(imageUrl: String, forImageView: WKInterfaceImage) {

NSURLSession.sharedSession().dataTaskWithURL(imageUrl, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let image = UIImage(data: data!) {
dispatch_async(dispatch_get_main_queue()) {
forImageView.setImage(image)
}
} else {
NSLog("could not load data from image URL: \(imageUrl)")
}
}).resume()
}

Loading images in WatchKit

Moving the images in a xcassettes file solved the issue.

How to show image while url is loading

You can resolve it in 2 different ways

  1. Inject JS code which will check document.ready state and show an image while not
  2. Add UIImageVIew as subview then

set isHidden property of the subview as false in WKNavigationDelegate method

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)

and as true in

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)



Related Topics



Leave a reply



Submit