ios - 如何从带有 JSON 数据的字符串中获取 UIImage
问题描述
我正在尝试从 API 加载图标图像OpenWeatherMap
,并将其显示在ImageView
. 我正在尝试将其加载到imageView
“ iconImage
”中。我已经成功加载了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)
}
}
}
解决方案
使用翠鸟
它在 ImageView 中创建一个扩展。你将使用self.imageview.kf.setImage(with: "url")
推荐阅读
- maven - 使用 maven 修改 POM 文件的设置以支持 Artifactory 上的访问令牌
- microsoft-graph-api - 当某个配置或策略停止应用于 intune 上的设备时,是否有办法获取警报
- swift - 命令行工具如何打印帮助文本并通过管道自动获取更多命令的行为?
- python - Django 仅返回默认图像 URL
- flutter - 在颤振中条件为真后如何弹出页面?
- javascript - EventListener 不能在 iframe 中工作,但可以在 iframe 之外工作
- node.js - 邮递员请求不起作用(Node.JS 和 MongoDB)
- r - 如何对R中的列进行滚动求和?
- oracle - 如何根据 Oracle Apex 中其他列的值启用或禁用列中的按钮?
- php - 注意:未定义索引:img in