从WatchKit上的URL加载图像

时间:2015-04-05 15:48:00

标签: swift watchkit apple-watch

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

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

8 个答案:

答案 0 :(得分:12)

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)

答案 1 :(得分:6)

这是类别

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)

答案 2 :(得分: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)

希望得到这个帮助。

答案 3 :(得分: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)
                }
            }
        }
    }
}

答案 4 :(得分: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)")
        }
    }
}

}

答案 5 :(得分: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中添加NSTransportSecurity。

答案 6 :(得分:0)

 result = Event.objects.filter(title__contains=key)

}

答案 7 :(得分: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)