• 主页
  • 随笔
  • 技术笔记
  • 全部文章
标签 友链 关于我

  • 主页
  • 随笔
  • 技术笔记
  • 全部文章

iOS 14 Widget小组件 (SwiftUI)

阅读数:次 2021-12-23
字数统计: 2.2k字   |   阅读时长≈ 10分

iOS14 Widget仅支持SwiftUI,支持在任意主界面上进行Widget页面的编辑,UI变成了三种尺寸,每一个Widget都是一个单独的组件,他们可以自己管理自己通过简单的长按下压手势进行编辑和删除操作。

一、iOS14 创建Widget

创建iOS的项目:

  • Create a new Xcode Project
  • 语言选择:Swift/OC

创建Widget组件:

  • File->New->Target添加Widget Extension Target 点击Next

  • 输入Widget组件名,取消勾选Include Configuration Intent,点击Finish就可以了。

  • 此时工程默认生成模板,可以看到Widget三个尺寸。

二、生命周期解读代码

1. Provider

  • 为小组件展示提供一切必要信息的结构体,实现TimelineProvider协议
1
2
3
4
5
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> SimpleEntry { ...... }
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> Void) { ...... }
func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) { ...... }
}
  • placeholder:提供一个默认的视图,当网络数据请求失败或者其他一些异常的时候,用于展示
  • getSnapshot:为了在小部件库中显示小部件,WidgetKit要求提供者提供预览快照,在组件的添加页面可以看到效果
  • getTimeline:在这个方法内可以进行网络请求,拿到的数据保存在对应的entry中,调用completion之后会到刷新小组件。
  • 请求时间线有两个地方:一个是按照策略请求,一个在请求即时快照时。
  • 刷新小组件并不能重新获取展示数据,只有重启时间线,才能重新获取数据。
  • 如果需要定义小组件的刷新策略为每分钟刷新,15分钟后重启时间线:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//设置时间线
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []

let currentDate = Date()
for hourOffset in 0 ..< 15 {
//设置刷新策略
let entryDate = Calendar.current.date(byAdding: .minute, value: hourOffset, to: currentDate)!
entries.append(simpleModel(entryDate))
}
//重启时间线策略
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
  • 关于重启策略,根据官方文档,每个配置的小部件每天接收有限的重启次数。有几个因素会影响小部件接收的重启次数,例如:包含的应用程序是在前台还是后台运行,小部件在屏幕上显示的频率,以及包含的应用程序参与的活动类型。
  • 根据我参考其他开发者的分享,设定在5分钟以下的重启时间线策略几乎无效。一般设定在15分钟以上的策略,才能按时重启时间线。
    策略有如下几种:
1
2
3
4
5
6
7
8
//在结束时重启
public static let atEnd: TimelineReloadPolicy
//从不重启

public static let never: TimelineReloadPolicy
//在某一时间点后重启

public static func after(_ date: Date) -> TimelineReloadPolicy

2. SimpleEntry

  • 实现TimelineEntry协议,就是用来保存所需要的数据。
  • 其中TimelineEntry含有date属性。
  • 可以继续添加其他的属性。例如自定义一个展示用的model:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Model {
let Title: String
let Image: UIImage
let ID: String
let Context: String
}

将Model添加到entry中
struct SimpleEntry: TimelineEntry {
let date: Date
let Obj1: Model
let Obj2: Model
let Obj3: Model
}

3. 加载入口

  • YourWidget是我们为组件设置的名字,模板自动使用这个名字帮我们生成了一个实现了Widget协议的结构体。
1
2
3
4
5
6
7
8
9
10
struct YourWidget: Widget {
let kind: String = "YourWidgetKind"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
YourWidgetEntryView(entry: entry)
}
.configurationDisplayName("---")
.description("---")
}
}
  • StaticConfiguration是系统提供的组件配置结构体,其用来对静态类型的组件提供配置。
  • kind:是Widget的唯一标识
  • StaticConfiguration:初始化配置代码
  • configurationDisplayName:添加编辑界面展示的标题
  • description:添加编辑界面展示的描述内容
  • supportedFamilies这里可以限制要提供三个样式中的哪几个
1
2
3
4
5
6
7
8
9
10
一个Widget只提供了三个样式的选择:大、中、小
如果需要展示多个Widget(最多5个):
struct YourWidgets: WidgetBundle {
@WidgetBundleBuilder
var body: some Widget {
Widget()
Widget2()
......
}
}

4. SwiftUI展示UI

1
2
3
VStack:垂直排列元素
HStack:水平排列元素
ZStack:堆叠排列元素
1
2
3
4
显示文本方法:
Text(entry. Obj1.Title)
.font(.system(size: 18))
.fontWeight(.bold)
1
2
3
4
显示图片方法:
Image(uiImage: entry. Obj1.Image)
.resizable()
.frame(width: 50, height: 50)

三、Widget与App交互及获取数据

1. 唤起APP跳转

  • systemSmall只能用widgetURL修饰符实现URL传递:
1
2
3
4
5
6
7
ZStack(content: {
Image(...)
VStack(alignment: .leading, spacing: 4) {
Text("...")
}
})
.widgetURL(URL(string: "abc://..."))
  • systemMedium、systemLarge可以用Link或者 widgetUrl处理:
1
2
3
4
5
6
7
8
9
Link(destination: URL(string: "abc://...")!){
HStack(content: {
Image(...)
VStack(alignment: .leading, spacing: 4) {
Text(...)
Text(...)
}
})
}

2. 主App传值到Widget

先使用开发者账号创建主App与Widget的group,生成groupid;
通过NSUserDefault或NSFileManager进行通信;

  • App存值:
1
2
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"groupId"];
[userDefaults setObject:dict forKey:key]];
  • Widget取值:
1
2
3
4
5
6
7
//从UserDefault中取值
func simpleModel(_ entryDate:Date) -> SimpleEntry
{
let object1: NSDictionary = UserDefaults(suiteName: "groupId")?.object(forKey: key1) as! NSDictionary
//可以继续添加obj2、obj3
return SimpleEntry(date: Date(), object: object1)
}

3. 加载网络图片

无法异步加载图片,只能同步加载

1
2
3
4
5
6
let Image:UIImage = {
if let iamgeData = try? Data(contentsOf: URL(string: “...” as!String)!) {
return UIImage(data: iamgeData)!
}
return UIImage(named: "")!
}()

4. 网络请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
static func request(completion: @escaping (Result<SimpleEntry, Error>) -> Void) {
let url = URL(string: "...")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
completion(.failure(error!))
return
}
let poetry = getDataFromJson(fromData: data!)
completion(.success(poetry))
}
task.resume()
}

static func getDataFromJson(fromData data: Data) -> SimpleEntry {
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
//因为免费接口请求频率问题,如果太频繁了,请求可能失败,这里做下处理,放置crash
guard let data = json["data"] as? [String: Any] else {
return SimpleEntry(加载失败的数据)
}
return SimpleEntry(...)
}

5. App主动刷新Widget

因为主动刷新小组件,仅支持swift。所以如果在OC原生环境中使用,需加入swift作为桥接。
创建 WidgetKitManager.swift文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import WidgetKit
@objc
@available(iOS 14.0, *)
class WidgetKitManager: NSObject {

@objc
static let shareManager = WidgetKitManager()

/// MARK: 刷新所有小组件
@objc
func reloadAllTimelines() {
#if arch(arm64) || arch(i386) || arch(x86_64)
WidgetCenter.shared.reloadAllTimelines()
#endif
}

/// MARK: 刷新单个小组件
/*
kind: 小组件Configuration 中的kind
*/
@objc
func reloadTimelines(kind: String) {
#if arch(arm64) || arch(i386) || arch(x86_64)
WidgetCenter.shared.reloadTimelines(ofKind: kind)
#endif
}
}

OC中使用刷新小组件:

1
2
3
4
5
6
if (@available(iOS 14.0, *)) {
//刷新所有小组件
[[WidgetKitManager shareManager] reloadAllTimelines];
//刷新单个小组件
[[WidgetKitManager shareManager] reloadTimelinesWithKind:@"KindId"];
}

四、用户属性配置

在第一次创建Widget的时候,有一个选项我们没有勾选,Include Configuration Intent。这选项主要是用来支持你自定义一些属性配置(例如天气组件,用户可以选择城市,股票组件,用户可以选择代码等)

1. 补充创建

菜单File ->New ->File然后找到Siri Intent Definition File之后添加到Widget中.
这里一定记得勾选。

添加Intent

将属性改为:

此时系统会根据你的命名生成一个只读文件:

2.设置可配置选项

这个选项设置完,就在上图中的代码上会有对应显示。

3.修改代码

1
import Intents

SimpleEntry添加ConfigurationIntent属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//从UserDefault中取值
func simpleModel(_ entryDate:Date, config:ConfigurationIntent) -> SimpleEntry
{
let object1: NSDictionary = UserDefaults(suiteName: "......")?.object(forKey: "......") as! NSDictionary
let object2: NSDictionary = UserDefaults(suiteName: "......")?.object(forKey: "......") as! NSDictionary
let object3: NSDictionary = UserDefaults(suiteName: "......")?.object(forKey: "......") as! NSDictionary

return SimpleEntry(date: Date(), configuration: config, Obj1: buildModel(object1), Obj2: buildModel(object2), Obj3: buildModel(object3))
}

//获取显示数据
func buildModel(_ dict:NSDictionary) -> Model
{
let modelImage:UIImage = {
if let iamgeData = try? Data(contentsOf: URL(string: dict.object(forKey: "ImageUrl") as!String)!) {
return UIImage(data: iamgeData)!
}
return UIImage(named: "")!
}()
let Model = WistTVModel(
Title: dict.object(forKey: "title") as! String,
Image: modelImage,
ID: dict.object(forKey: "ID") as! String,
Context: dict.object(forKey: "Context") as! String
)
return Model
}

struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationIntent
let Obj1: Model
let Obj2: Model
let Obj3: Model
}

TimelineProvider -> IntentTimelineProvider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct Provider: TimelineProvider {
//设置默认视图
func placeholder(in context: Context) -> SimpleEntry {
simpleModel(Date(), config: ConfigurationIntent())
}
//小部件库中显示小部件,设置快照
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = simpleModel(Date(), config: configuration)
completion(entry)
}

//设置时间线
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []

let currentDate = Date()
for hourOffset in 0 ..< 15 {
//设置刷新策略
let entryDate = Calendar.current.date(byAdding: .minute, value: hourOffset, to: currentDate)!
entries.append(simpleModel(entryDate, config: configuration))
}
//重启时间线策略
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}

StaticConfiguration -> IntentConfiguration

1
2
3
4
5
6
7
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
YourWidgetEntryView(entry: entry)
}
.configurationDisplayName("YourWidget")
.description("YourWidget description")
}

显示

1
Text(entry.configuration.parameter == nil ? "没有值" : entry.configuration.parameter!)

五、优化及调试

1. 优化

在widget使用数据之前,App应已经准备数据。使用共享组group存储数据。
让App使用后台处理时间来更新widget数据。
选择最合适的刷新策略。
仅当小部件当前显示的信息更改时,才调用reloadtimelines。

2. 调试

在Xcode中调试时,WidgetKit不会施加刷新次数限制。要验证Widget的行为是否正确,需使用真机测试。

  • 本文作者: Grx
  • 本文链接: https://ruixiaoguo.github.io/Grx.github.io/Grx.github.io/2021/12/23/iOS 14 Widget小组件 (SwiftUI)/
  • 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!
  • OC

扫一扫,分享到微信

抖音工程架构演进
今年最值得关注的 23 种新移动技术
  1. 1. 一、iOS14 创建Widget
    1. 1.0.1. 创建iOS的项目:
    2. 1.0.2. 创建Widget组件:
  • 2. 二、生命周期解读代码
    1. 2.1. 1. Provider
    2. 2.2. 2. SimpleEntry
    3. 2.3. 3. 加载入口
    4. 2.4. 4. SwiftUI展示UI
  • 3. 三、Widget与App交互及获取数据
    1. 3.1. 1. 唤起APP跳转
    2. 3.2. 2. 主App传值到Widget
    3. 3.3. 3. 加载网络图片
    4. 3.4. 4. 网络请求
    5. 3.5. 5. App主动刷新Widget
  • 4. 四、用户属性配置
    1. 4.1. 1. 补充创建
    2. 4.2. 2.设置可配置选项
      1. 4.2.1. 这个选项设置完,就在上图中的代码上会有对应显示。
    3. 4.3. 3.修改代码
  • 5. 五、优化及调试
    1. 5.1. 1. 优化
    2. 5.2. 2. 调试
  • © 2014-2024 Grx
    GitHub:hexo-theme-yilia-plus by Litten
    本站总访问量次 | 本站访客数人
    • 标签
    • 友链
    • 关于我

    tag:

    • life
    • OC
    • Google
    • Fastlane
    • Flutter
    • hexo
    • 智能家居
    • Apple Watch
    • 逆向
    • Lottie
    • PHP
    • cocos2d
    • Mac
    • MonkeyKing
    • RN
    • Swift
    • RAC
    • WKWebView
    • WebView
    • Xcode
    • xcode
    • ios
    • Android
    • appledoc
    • MMKV
    • LLVM
    • FreamWork






      
      

    • 唐巧的博客
    • 王巍(喵神)OneVsDen
    • 阿里“念纪“
    • 滴滴-戴铭
    • 郭曜源(ibireme)
    • 阿里”南栀倾寒“
    • 蘑菇街李忠
    • 码农人生
    • 玉令天下
    • bang
    • Ian的博客
    这里是Grx的个人博客:
    iOS开发工程师一枚
    联系方式:
    QQ:1217255509
    Email:grx0917@sina.com
    知识管理,时间管理,自我管理,架构即未来
    欢迎技术交流!