如何在Swift应用程序中在屏幕上显示图标?

时间:2018-05-25 20:08:15

标签: json swift image

我写了一个简单的应用程序,显示某些城市的天气,你可以写入搜索栏。

应用程序从JSON(JSON请求的一部分)获取此信息:

@IBOutlet weak var imageView: UIImageView!
var image = UIImage()

下载图标肯定有效,因为有时候我会看到图像,但通常不会。

DispatchQueue.main.sync {
    if errorHasOccured {
        self?.cityLabel.text = "Uncnown city"
        self?.temperatureLabel.text = ""
    } else {
        self?.cityLabel.text = locationName
        self?.temperatureLabel.text = "\(temperature!)"
        self?.imageView.image = image
    }

}

分配给全局变量的代码位于主线程中。

.html

如何做到这一点?

完整代码:https://pastebin.com/jbzgQyPN

1 个答案:

答案 0 :(得分:0)

您将图像设置在错误的位置。您在后台线程中的任务,因此您需要在响应到来时在imageView上添加图像。

        let downloadPicTask = session.dataTask(with: iconURL!) { (data, response, error) in
            // The download has finished.
            if let e = error {
                print("Error downloading cat picture: \(e)")
                print(2)
            } else {
                print(3)
                // No errors found.
                // It would be weird if we didn't have a response, so check for that too.
                if let res = response as? HTTPURLResponse {
                    print("Downloaded cat picture with response code \(res.statusCode)")
                    if let imageData = data {
                        // Finally convert that Data into an image and do what you wish with it.
                        image = UIImage(data: imageData)!
                       /// ****You have to set the image here***
                        self?.imageView.image = image

                        print(3)
                        // Do something with your image.
                    } else {
                        print("Couldn't get image: Image is nil")
                    }
                } else {
                    print("Couldn't get response code for some reason")
                }
            }
        }