Widget 加载网络图片,在func timeline(withcompletion)
这个方法中请求拿到图片链接后,必须同步把图片解析出来,否则直接让对应的WidgetView
去load url 是加载不出来的.
这么写好像是不行的。
// beautiful 该图片的比例 1.6:1
struct SWidgetEntryView : View {
var entry: Provider.Entry
@State private var image : UIImage? = nil
let defaultImage = UIImage(named: "beautiful")!
var body: some View {
VStack (alignment:.center){
GeometryReader {//获取父视图的大小
proxy in
Image(uiImage: self.image ?? defaultImage) //头部图片
.resizable()
.aspectRatio(contentMode:.fit)
.frame(width: proxy.size.width, height: proxy.size.width/1.6)
.onAppear(perform:loadImage)
}
HStack (alignment:.center, spacing:25){
ForEach(0 ..< WidgetModels.count){ //循环个数
index in
let mode = WidgetModels[index]
Link(destination: URL(string: mode.linkUri)!){ //点击事件
VStack{
Image(mode.icon as String) //icon 展示图
.resizable()
.frame(width: 60, height: 60, alignment: .center)
Text(mode.name as String) //文字展示
.frame(width: .infinity, height: 20, alignment: .center)
.foregroundColor(.black)
.font(.system(size: 15))
}
}
}
}
Spacer(minLength: 40)
}
}
func loadImage() {
guard let url = URL(string: "https://v1.alapi.cn/api/bbcover?c=av86863038") else { return }
URLSession.shared.dataTask(with: url){ (data, response, error) in
let json = try! JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
guard let data = json["data"] as? [String: Any] else {
return print("解析失败")
}
let cover = data["cover"]
print(cover as Any)
if let imageData = try? Data(contentsOf: URL(string: cover as! String)!){
image = UIImage(data: imageData)
}
}.resume()
}
}
下面是正确的写法
//Provider 简单理解,这是一个数据提供对象,用来为小组件提供渲染数据,其必须实现TimelineProvider协议,即是基于时间线来驱动小组件的渲染。
struct Provider: TimelineProvider {
//placeholder 提供一个占位的视图,当小组件没有数据或者在锁屏状态时,会显示这个占位视图。
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(),model: WidgetModels[0],imgModel:imageModels[0])
}
//getSnapshot:快照预览为了在小部件库中显示小部件,在你添加widget时候,预览的样式。当部件还没有从服务器获取状态时,Provider通过显示一个空状态来实现getSnapshot方法
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date(),model: WidgetModels[0],imgModel:imageModels[0])
completion(entry)
}
//getTimeline:在请求初始快照后,WidgetKit调用getTimeline(for:with:completion:)向提供者请求一个常规的时间线。时间线由一个或多个时间线条目和一个重载策略组成,告知WidgetKit何时请求后续时间线。
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
//间隔2分钟请求一次新的数据
let entryDate = Calendar.current.date(byAdding: .minute, value: 2, to: currentDate)!
Srequest.request { result in
let imgModel: imageModel
if case .success(let response) = result {
imgModel = response
} else {
imgModel = imageModel(id: 0, image: UIImage(named: "beautiful")!)
}
let entry = SimpleEntry(date: entryDate,model: WidgetModels[0],imgModel:imgModel)
//Widget的刷新策略
//atEnd: timeline 中最后一个 entry 显示后更新。timelines 方法会重新调用。
//after(date): 指定日期,重新更新timeline。
//never:系统不会自动更新,除非我们主动通过 Widget Center Api 来更新。
let timeline = Timeline(entries: [entry], policy: .after(entryDate))
completion(timeline)
}
}
}
//请求数据
struct Srequest {
static func request(completion: @escaping (Result<imageModel, Error>) -> Void) {
//这个接口网上找的
let url = URL(string: "https://api.uomg.com/api/rand.avatar?sort=%E7%94%B7&format=json")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
completion(.failure(error!))
return
}
let json = try! JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
let imgurl = json["imgurl"] ?? "1"
var image : UIImage = UIImage(named: "beautiful")!
print(json["imgurl"] as Any)
if let imageData = try? Data(contentsOf: (URL.init(string: imgurl as! String) ?? URL(string: "1"))!){
image = UIImage(data: imageData)!
}
completion(.success(imageModel(id: 0, image: image)))
}
task.resume()
}
}
期间有遇到图片加载不出来的问题,这个问题也是找了好久。
如果有遇到这个问题,检查一下这个图片地址是不是https
//http 获取的data 是 nil
Data(contentsOf: (URL.init(string: imgurl as! String) ?? URL(string: "1"))!)
另外也可以设置:Widget
->Info.plist
->App Transport Security Settings
添加Allow Arbitrary Loads
YES
,这样就兼容了http
iOS14 Widget从开发到上线 (一)
iOS14 Widget从开发到上线 (二)
iOS14 Widget从开发到上线 (四)
iOS14 Widget从开发到上线 (五)