【问题标题】:Swift image from URL not showing来自 URL 的 Swift 图像未显示
【发布时间】:2015-03-10 12:48:32
【问题描述】:

我是 swift 新手,不知道为什么要从 url 加载图像。 代码:

        let url = NSURL(string: imageURL)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
        println("Should load the pic!")
        var profilePic = UIImage(data: data)
        self.profileImage.setImage(profilePic)
    })

在我的界面控制器中,我有一个名为“profileImage”的图像,它与一个 IBOutlet 链接。我注意到的一件事是“应该加载图片!”没有出现在控制台中,所以它没有进入 setImage 代码..

【问题讨论】:

    标签: ios xcode swift


    【解决方案1】:

    当您从 URL 下载图像时。我建议您在后台执行此操作。这是给你的示例代码:

    import UIKit
    
    class ViewController: UIViewController {
    
    @IBOutlet weak var profileImage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
    
        profileImage.contentMode = UIViewContentMode.ScaleAspectFit
        if let checkedUrl = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
            downloadImage(checkedUrl)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func getDataFromUrl(urL:NSURL, completion: ((data: NSData?) -> Void)) {
        NSURLSession.sharedSession().dataTaskWithURL(urL) { (data, response, error) in
            completion(data: NSData(data: data))
            }.resume()
    }
    
    func downloadImage(url:NSURL){
        println("Started downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
        getDataFromUrl(url) { data in
            dispatch_async(dispatch_get_main_queue()) {
                println("Finished downloading \"\(url.lastPathComponent!.stringByDeletingPathExtension)\".")
                self.profileImage.image = UIImage(data: data!)
            }
        }
    }
    }
    

    【讨论】:

    • 这是给 Watchkit 的。我在 self.profileImage.image = UIImage(data: data!) 上遇到错误。也就是说“WKInterfaceImage”没有名为“image”的成员
    • 我只是给你一个例子..根据你的需要更改代码..:)
    • 很高兴为您提供帮助..:)
    【解决方案2】:

    试试这个,它可能对你有帮助:

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        var profilePic =  UIImage(data: NSData(contentsOfURL: NSURL(string:"http://devhumor.com/wp-content/uploads/2012/04/devhumor.com_pointers.png")));
    
        self.profileImage.setImage(profilePic);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多