从WatchKit上的URL加载图像

问题描述 投票:8回答:8

是否有更优雅的解决方案在手表上加载外部图像而不是以下?

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)
    }
}
swift watchkit apple-watch
8个回答
13
投票

NSURL旨在用于本地文件。而是使用NSURLSession。设置远程图像的比例也很有用。

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

像这样使用它

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

7
投票

这是类别

import WatchKit

public extension WKInterfaceImage {

    public func setImageWithUrl(url:String) -> WKInterfaceImage? {

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

            dispatch_async(dispatch_get_main_queue()) {
                self.setImage(placeholder)
            }
        }

        return self
    }

}

像这样使用它

 self.imageView.setImageWithUrl(image_url)

5
投票

我认为这个解决方案很好,因为当你试图从网上加载一些图像时,它可以帮助你的应用程序摆脱困境。你可以创建一个像这样的新函数:

func loadImage(url:String, forImageView: WKInterfaceImage) {
// load image
    let image_url:String = url
    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()) {
            forImageView.setImage(placeholder)
        }
    }

}

在那之后你想从urlString加载图片的任何地方你都可以像这样使用:

loadImage("http://...", forImageView: self.myImageView)

希望这有帮助。


4
投票

我认为通过这个解决方案,您可以将图像存储在缓存中并从缓存中显示图像。因此您可以调用此函数并使用它。

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

    forImageView.setImageNamed("placeholder")
    let image_url:String = url

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

        let url:NSURL = NSURL(string:image_url)!
        print(url)

        //if image is already stored in cache
        if WKInterfaceDevice.currentDevice().cachedImages[image_url] != nil{
            dispatch_async(dispatch_get_main_queue()) {
                forImageView.setImageNamed(image_url)
            }
        }else{
            if let data = NSData(contentsOfURL: url){

                //load image
                let image = UIImage(data: data)!
                //Store image in cache
                WKInterfaceDevice.currentDevice().addCachedImage(image, name: image_url)
                dispatch_async(dispatch_get_main_queue()) {
                    forImageView.setImage(placeholder)
                }
            }
        }
    }
}

1
投票

刚刚完成了相同的任务,这里的答案对我有所帮助,但我需要做一些修改。所以我想在这里分享更新版本(没有任何强制解包)常见答案(应该适用于Swift 4.2):

public extension WKInterfaceImage {

public func setBackgroundImage(url: String) {
    let asyncQueue = DispatchQueue(label: "backgroundImage")
    asyncQueue.async {
        do {
            if let url = URL(string: url) {
                let data = try Data(contentsOf: url)
                if let placeholder = UIImage(data: data) {
                    self.setImage(placeholder)
                }
            }
        } catch let error {
            print("Could not set backgroundImage for WKInterfaceImage: \(error.localizedDescription)")
        }
    }
}

}


0
投票
     if let url = NSURL(string: "http://google.net/img/upload/photo2.png") {
            if let data = NSData(contentsOfURL: url){

             imageWK.setImage(UIImage(data: data))

        }
    }

试试这个代码。不要忘记在Plist中添加NSAPPTransportSecurity。


0
投票
public extension WKInterfaceImage {

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

        URLSession.shared.dataTask(with: NSURL(string: url)! as URL) { data, response, error in
            if (data != nil && error == nil) {
                let image = UIImage(data: data!, scale: scale)

                DispatchQueue.main.async() {
                   self.setImage(image)
                }
        }
        }.resume()

    return self
}

}


0
投票

Swift 4.2

使用URLSession,正确的GCD和@discardableResult来静音Result of call to '...' is unused警告。

plist中 App Transport Security Settings Allow Arbitrary Loads - YES

如果您愿意,可以在故事板中将固定图像大小设置为100x100。

let url = "https://i.imgur.com/UZbLC0Q.jpg"

public extension WKInterfaceImage {

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

        URLSession.shared.dataTask(with: NSURL(string: url)! as URL) { data, response, error in
            if (data != nil && error == nil) {
                let image = UIImage(data: data!, scale: scale)

                DispatchQueue.main.async {
                    self.setImage(image)
                }
            }
            }.resume()

        return self
    }
}

呼叫

row.image.setImageWithUrl(url: url, scale: 1.0)
© www.soinside.com 2019 - 2024. All rights reserved.