ios - 下载的图像未显示 iOS Swift

标签 ios swift image request nsurl

我刚刚开始学习如何在 iOS Swift 中发出网络请求。下面是一个非常简单的图像请求,似乎一切正常。该任务下载图像时没有错误,但 imageView 从不显示下载的图像。任何帮助将不胜感激。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let imageURL = NSURL(string: "https://en.wikipedia.org/wiki/Baseball#/media/File:Angels_Stadium.JPG")!

        let task = NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, response, error) in
            if error == nil {
                let downloadedImage = UIImage(data: data!)
                performUIUpdatesOnMain {
                    self.imageView.image = downloadedImage
                }
            }
        }
        task.resume()
    }
}

最佳答案

除了您使用的是错误的 URL 并且您的 downloadedImage 即将出现 nil 之外,您的代码工作正常,因为它无法为此数据创建 UIImage,正确的 URL 是:

https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Angels_Stadium.JPG/1920px-Angels_Stadium.JPG

将您的代码更新为上面的代码,一切都应该可以正常工作:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let imageURL = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Angels_Stadium.JPG/1920px-Angels_Stadium.JPG")!

    let task = NSURLSession.sharedSession().dataTaskWithURL(imageURL) { (data, response, error) in

        guard error == nil, let data = data else { return }

        let downloadedImage = UIImage(data: data)
        dispatch_async(dispatch_get_main_queue()) {
            self.imageView.image = downloadedImage
        }
    }
    task.resume()
}

希望对你有帮助

关于ios - 下载的图像未显示 iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37231578/

相关文章:

python - 损坏的图像 - Google App Engine

python - 使用 Image Viewer (Eye of GNOME) 在一个目录中打开多个图像

iOS 应用程序崩溃日志地址簿

ios - OpenGL 与 Cocos2d : What to choose?

Swift 5 结果类型

swift - 从后台操作在 NSView 中绘制无效

java - JComboBox(JList) - 每个单元格的可点击图像

ios - 通过 UIActivityViewController 发送自定义数据

ios - 将第一个字母设为粗体 - ios swift

ios - 符合自定义协议(protocol)的通用函数 - Swift