image - ios 小部件在 TimelineProvider 中加载远程图像 url?
问题描述
我在我的小部件上显示了一个股票图表(例如:https ://example.com/my_img.png )。
作为对 SO & Apple dev 4rum 的调查,我找不到可行的解决方案。
据我所知,Widget 不支持异步图像加载,所以我的方法是在我们 getTimeline() 时获取图像,然后将图像数据传递到 Entry 以便稍后显示。
但我不能让它工作,谁能指出我如何解决它?
简而言之,它不起作用!:
// Fetch first in getTimeline()
let imgData = Data(
contentsOf: URL(string: "https://example.com/my_img.png")!
)!
// Then render it later in View
Image(uiImage: UIImage(data: imgData))
这是我所有的伪代码:
func getTimeline(...) {
var imageData = nil
let url: URL = URL(string: "https://example.com/my_img.png")!
if let imgData:Data = try? Data(contentsOf: url) {
imageData = imgData
}
var entry = SimpleEntry(...)
entry.imageData = imageData
let timeline = Timeline(entries: [entry], policy: .atEnd)
completion(timeline)
}
// Some where in the widget i'll show the imageData above
struct FIM_SV_Chart: View {
let imageData: Data?
var body: some View {
if imageData != nil, let uiImage = UIImage(data: imageData!) {
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 80, height: 26.0)
} else {
Image("EmptyChart")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 80, height: 26.0)
}
}
}
非常感谢。
解决方案
这是我的错,我生成了一个不正确的图像 url,所以 imgData 是 0 字节!
这将起作用:
// Fetch first in getTimeline()
let imgData = Data(
contentsOf: URL(string: "https://example.com/my_img.png")!
)!
// Then render it later in View
Image(uiImage: UIImage(data: imgData))
推荐阅读
- javascript - 在 Mongo 指南针中查看 Mongo DB
- python - Adding properties dynamically to a Python class that point to items in a dictionary
- git - 如何从一个分支复制到另一个 - 要掌握的文件?
- excel - 引用范围内单元格值的方式之间的差异
- version-control - Mercurial Repo:hg 验证问题:“第一个损坏的变更集似乎是 3270”
- c# - 编辑具有特定索引的列表时会打印额外的代码
- ldap - 使用 ldapjs 创建与 OpenLDAP 服务器的 LDAP 连接的最佳方法是什么?
- r - 如何使用循环将值替换为基于 r 数据框中另一列的平均值
- python - 为什么 plotly graph 的 Scattergl 不适用于散点图
- java - 如何跟踪方法内的参数?