首页 > 解决方案 > 如何从带有 JSON 数据的字符串中获取 UIImage

问题描述

我正在尝试从 API 加载图标图像OpenWeatherMap,并将其显示在ImageView. 我正在尝试将其加载到imageViewiconImage”中。我已经成功加载了JSON位置和湿度的数据,因为它们是Strings,但图标数据也是 a String,我无法将其显示为UIImage

下面的代码:

我的 JSON 结构如下:

struct Coordinate : Decodable {
        let lat, lon : Double?
    }

    struct Weather : Decodable {
        var id : Int?
        var main, myDescription, icon : String?

        enum CodingKeys : String, CodingKey {
            case id = "id"
            case main = "main"
            case icon = "icon"
            case myDescription = "description"
        }
    }

    struct Sys : Decodable {
        let type, id : Int?
    let sunrise, sunset : Date?
    let message : Double?
    let country : String?
}

struct Main : Decodable {
    let temp, tempMin, tempMax : Double?
    let pressure, humidity : Int?
}

struct Wind : Decodable {
    let speed : Double?
    let deg : Int?
}

struct MyWeather : Decodable {
    let coord : Coordinate?
    let cod, visibility, id : Int?
    let name : String?
    let base : String?
    let weather : [Weather]?
    let sys : Sys?
    let main : Main?
    let wind : Wind?
    let dt : Date?
}`enter code here`    

查看下面的控制器:

  guard let APIUrl = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=" + text +  "&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric") else { return }
    //API KEY

    URLSession.shared.dataTask(with: APIUrl) { data, response, error in
        guard let data = data else { return }


        let decoder = JSONDecoder()
        //Decoder

        do {

if (self.iconImage != nil)
                {
                    if let gicon = weatherData.weather?.first?.icon {
                        DispatchQueue.main.async {
                            self.iconImage.image! =  gicon
                        }
                    }
                }
                if (self.LocationLabel != nil)
                {
                    if let gmain = weatherData.name {
                        print(gmain)
                        DispatchQueue.main.async {
                            self.LocationLabel.text! = "Current Weather in: " + String (gmain)
                        }
                    }
                }


                if (self.HumidityLabel != nil)
                {
                    if let ghumidity = weatherData.main?.humidity
                    {
                        print(ghumidity, "THIS IS HUMIDITY")
                        DispatchQueue.main.async {
                            self.HumidityLabel.text! = String (ghumidity)
                        }
                    }
                }

标签: iosswiftapiuiimageopenweathermap

解决方案


使用翠鸟

它在 ImageView 中创建一个扩展。你将使用self.imageview.kf.setImage(with: "url")


推荐阅读