gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:14:48 26 4
gpt4 key购买 nike

我正在尝试从 API OpenWeatherMap 加载图标图像,并将其显示在 ImageView 中。我正在尝试将其加载到 imageView 'iconImage' 中。我已成功加载位置和湿度的 JSON 数据,因为它们是 Strings,但图标数据也是 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`

查看下面的 Controller :

  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)
}
}
}

最佳答案

使用Kingfisher

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

关于ios - 如何从带有 JSON 数据的字符串中获取 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51847803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com