上一篇文章【iOS14】仿網(wǎng)易云桌面小組件(一)介紹了如果創(chuàng)建小組件,并使用SwiftUI
簡(jiǎn)單實(shí)現(xiàn)了網(wǎng)易云小組件的界面,本篇將從網(wǎng)絡(luò)請(qǐng)求翅楼,圖片同步韵吨,動(dòng)態(tài)數(shù)據(jù)展示等方面來(lái)對(duì)小組件進(jìn)行優(yōu)化缎讼。
通過(guò)本篇文章你將學(xué)到以下幾點(diǎn)
1专执、SwiftUI中的網(wǎng)絡(luò)請(qǐng)求肩祥,圖片同步下載
2飞几、動(dòng)態(tài)刷新小組件
3砚哆、小組件中參數(shù)傳遞,綁定數(shù)據(jù)循狰,實(shí)現(xiàn)如下效果
SwiftUI中的網(wǎng)絡(luò)請(qǐng)求窟社,圖片同步下載
首先我們根據(jù)內(nèi)容先來(lái)定義數(shù)據(jù)模型
struct GKWYData {
let title: String // 標(biāo)題
let desc: String // 描述
let icon: String // 圖標(biāo)名稱
let bg: String // 背景圖片名稱
var bgImage: UIImage? = UIImage(named: "background") // 背景圖片對(duì)象
}
// 創(chuàng)建默認(rèn)數(shù)據(jù)
let defaultData = GKWYData(title: "每日音樂推薦", desc: "為你帶來(lái)每日驚喜", icon: "cm4_disc_type_list", bg: "leida_bg")
我們創(chuàng)建一個(gè)類GKWYDataLoader,然后定義靜態(tài)方法獲取每日音樂推薦绪钥,代碼如下:
struct GKWYDataLoader {
/// 請(qǐng)求推薦內(nèi)容
/// - Parameter completion: 請(qǐng)求完成回調(diào)
static func request(completion: @escaping (GKWYData) -> Void) {
// 熱門音樂列表接口灿里,成功后用隨機(jī)設(shè)置一個(gè)音樂為推薦音樂
// 如果獲取不到則使用默認(rèn)數(shù)據(jù),保證不能為空
let url = URL(string: "https://musicapi.qianqian.com/v1/restserver/ting?format=json&from=ios&channel=appstore&method=baidu.ting.billboard.billList&type=1&size=20&offset=0")!
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if data != nil && error == nil {
let json = try! JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
let error_code = json["error_code"] as! Int
if error_code == 22000 {
if let list = (json["song_list"] as? [[String: Any]]) {
// 獲取隨機(jī)數(shù)
let random = arc4random() % UInt32(list.count)
let item = list[Int(random)]
let title = item["title"] as! String
let author = item["author"] as! String
let album = item["album_title"] as! String
let desc = author + "-" + album
let cover = item["pic_radio"] as! String
var image: UIImage? = UIImage(named: "background")
// 同步網(wǎng)絡(luò)圖片到本地
if let data = try? Data(contentsOf: URL(string: cover)!) {
image = UIImage(data: data)
}
let wyData = GKWYData(title: title, desc: desc, icon: "cm4_disc_type_list", bg: "", bgImage: image)
completion(wyData)
}else {
completion(defaultData)
}
}else {
completion(defaultData)
}
}else {
completion(defaultData)
}
}.resume()
}
}
2程腹、動(dòng)態(tài)刷新小組件
給SimpleEntry增加數(shù)據(jù)模型
struct SimpleEntry: TimelineEntry {
let date: Date
let data: GKWYData
}
修改Provider里面的getTimeline方法如下匣吊,每隔5分鐘刷新一次數(shù)據(jù)
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
let currentDate = Date()
let updateDate = Calendar.current.date(byAdding: .minute, value: 5, to: currentDate)
GKWYDataLoader.request { (data) in
let entry = SimpleEntry(date: currentDate, data: data)
let timeline = Timeline(entries: [entry], policy: .after(updateDate!))
completion(timeline)
}
}
3、小組件中參數(shù)傳遞寸潦,綁定數(shù)據(jù)
在GKWYWidgetView中增加數(shù)據(jù)模型色鸳,并綁定數(shù)據(jù)
struct GKWYWidgetView: View {
let data: GKWYData
var body: some View {
GeometryReader { geo in
ZStack(alignment: .bottomLeading) {
// 添加背景圖
Image(uiImage: data.bgImage!)
.resizable()
// 添加陰影
LinearGradient(gradient: Gradient(colors: [Color.black.opacity(0.15), Color.black.opacity(0.35)]), startPoint: .top, endPoint: .bottom)
// 添加logo
Image("cm2_clock_logo")
.resizable()
.scaledToFill()
.frame(width: 20, height: 20)
.position(x: geo.size.width - (20/2) - 10, y: (20/2) + 10)
.ignoresSafeArea(.all)
// 添加左下角的圖標(biāo)及文字
VStack(alignment: .leading, spacing: 5) {
HStack() {
Image(data.icon)
.resizable()
.frame(width: 20, height: 20)
Text(data.title)
.font(.system(size: 16))
.foregroundColor(.white)
}
Text(data.desc)
.font(.system(size: 14))
.foregroundColor(.white)
}.padding()
}
}
}
}
修改GKWYWidgetEntryView并傳遞數(shù)據(jù)
struct GKWYWidget2EntryView : View {
var entry: Provider.Entry
var body: some View {
GKWYWidgetView(data: entry.data)
}
}
然后運(yùn)行小組件,就可以看到下面的效果
至此见转,小組件中動(dòng)態(tài)顯示網(wǎng)絡(luò)數(shù)據(jù)就已經(jīng)完成命雀。
最后
本篇文章我們學(xué)到了從網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)并在小組件中動(dòng)態(tài)顯示,接下來(lái)將會(huì)介紹給小組件增加可編輯功能
---敬請(qǐng)期待
參考資料
iOS14 Widget小組件開發(fā)實(shí)踐2——自定義Widget
網(wǎng)易云音樂 iOS 14 小組件實(shí)戰(zhàn)手冊(cè)