如何从带有JSON数据的字符串中获取UIImage

时间:2018-08-14 18:34:10

标签: ios swift api uiimage openweathermap

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

以下代码:

我的JSON结构如下:

UIImage

下面的视图控制器:

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`    

2 个答案:

答案 0 :(得分:0)

图标是图片的ID,您需要将其附加到此网址并加载

  

http://openweathermap.org/img/w/10d.png //这里------ id = 10d

假设您将使用SDWebImage,然后执行

let urlStr = "http://openweathermap.org/img/w/\(gicon).png"
self.iconImage.sd_setImage(with: URL(string:urlStr), placeholderImage: UIImage(named: "placeholder.png"))

请参见Docs

答案 1 :(得分:0)

使用Kingfisher

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