微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

天气图标未显示在天气 pp 的 imageview 中

如何解决天气图标未显示在天气 pp 的 imageview 中

我正在使用 openweathermap api 开发天气应用程序,我获取并设置了所有数据,还获取字符串中的图像名称,但天气图标未显示在 imageview 中。

import UIKit
import Alamofire

class Weatherviewmodel{
    
    var modelWeather2 = [MyWeatherData]()
    
    weak var vc: ViewController?
    
    func getWeather() {
        
        AF.request("http://api.openweathermap.org/data/2.5/weather?q="+(vc?.cityTextField.text)!+"&units=metric&appid=88236c7916643a06e2cd64d56f4e5077",method: .get).response{
            
            response in
            
//            debugPrint(response)
            if let data = response.data
            {
                do{
                    let apiResponse = try JSONDecoder().decode(MyWeatherData.self,from: data)
                    self.modelWeather2.append(apiResponse)

                    debugPrint(apiResponse)
                    dispatchQueue.main.async {
                        
                        self.vc?.tempLabel.text = String(apiResponse.main.temp)
                        self.vc?.titleLabel.text = apiResponse.weather[0].main
                        self.vc?.descriptionLabel.text = apiResponse.weather[0].description
                        let iconUrl = "http://openweathermap.org/img/wn/\(apiResponse.weather[0].icon).png"
                        self.vc?.weatherImage.image = UIImage(named: iconUrl)
                    }
                }catch let error{
                    print(error.localizedDescription)
                }
            }
        }
        
        
    }
}

这是我的代码

解决方法

您可以像下面发布的那样使用原始解决方案

extension UIImageView {
    func downloadImage(for url: String) {
        DispatchQueue.global(qos: .default).async {
            if let url = URL(string: url),let data = try? Data(contentsOf: url),let image = UIImage(data: data) {
                self.image = image
            }
        }
    }
}

最后你可以把它当作

self.vc?.weatherImage.downloadImage(for: "YOUR_URL_HERE")

同样,解决方案非常原始,除了简单地下载图像外,不提供缓存功能或任何其他功能

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。