由于近期在开发桌面小组件,将遇到的一些问题和小知识点记录一下。
WidgetKit 桌面小组件-管理多套组件
一般情况下,我们会将某一功能汇总在一套小组件,因此,可能我们会开发多套小组件以实现不同的业务功能。
1.主入口
Main_Extension.swift
import SwiftUI
@main
struct Widgets: WidgetBundle {
@WidgetBundleBuilder
var body: some Widget {
Widget_Extension()
Extension_Two()
}
}
@main标识符 用于声明小组件的入口,当我将@main标识符添加在Widgets上,在添加我们APP对应小组件时,就可以看到多套小组件了。
当我们将@main 标识符添加在 Widget_Extension(其中一套小组件)上,在桌面添加小组件时,就只能看到组件一了。
2.组件一 (Widget_Extension() )
import WidgetKit
import SwiftUI
import Intents
struct Provider: IntentTimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), configuration: ConfigurationIntent())
}
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date(), configuration: configuration)
completion(entry)
}
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate, configuration: configuration)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationIntent
}
struct Widget_ExtensionEntryView : View {
var entry: Provider.Entry
var body: some View {
Text(entry.date, style: .time)
}
}
struct Widget_Extension: Widget {
let kind: String = "Widget_Extension"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
Widget_ExtensionEntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
}
}
struct Widget_Extension_Previews: PreviewProvider {
static var previews: some View {
Widget_ExtensionEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent()))
.previewContext(WidgetPreviewContext(family: .systemSmall))
}
}
3.组件二(Extension_Two())
import WidgetKit
import SwiftUI
import Intents
struct Extension_Two_Provider: IntentTimelineProvider {
func placeholder(in context: Context) -> Extension_Two_Entry {
Extension_Two_Entry(date: Date())
}
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Extension_Two_Entry) -> ()) {
let entry = Extension_Two_Entry(date: Date())
completion(entry)
}
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [Extension_Two_Entry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = Extension_Two_Entry(date: entryDate)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct Extension_Two_Entry: TimelineEntry {
let date: Date
}
struct Extension_TwoEntryView : View {
var entry: Extension_Two_Provider.Entry
var body: some View {
Text(entry.date, style: .time)
}
}
struct Extension_Two: Widget {
let kind: String = "Extension_Two"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Extension_Two_Provider()) { entry in
Extension_TwoEntryView(entry: entry)
}
.configurationDisplayName("My Widget Extension_Two")
.description("Extension_Two.")
}
}
WidgetKit 桌面小组件-区分组件大小
同一套小组件,我们可以添加三种尺寸的组件。在组件代码中,我们可以使用如下环境变量来取得当前view的尺寸。
@Environment(\.widgetFamily) var family
假如某组件需要大中小三种类型展示不同的view,可参照如下设置
@Environment(\.widgetFamily) var family
@ViewBuilder
var body: some View {
switch family {
case .systemSmall:
Text("小组件-中杯")
case .systemMedium:
Text("小组件-大杯")
case .systemLarge:
Text("小组件-特大杯")
default:
Text("小组件-默认给个中杯的")
}
}
卡片类型 | 对应尺寸 |
---|---|
systemSmall | 小型 |
systemMedium | 中 |
systemLarge | 大 |
WidgetKit 桌面小组件-与宿主APP共享值
当APP中有些值,例如用户登录信息等,我们需要在小组件中使用,但是我们是无法直接通过宿主APP传给小组件的,这时候就需要将值(轻型)使用userDefaults存储,在小组件中取出。
1.使用开发者账号创建主APP与小组件的group,生成groupid
2.创建NSUserDefaults,主APP存储值
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.cocoajason.SwiftUIAndAppDemo"];
3.小组件创建NSUserDefaults取值
let object: String = UserDefaults(suiteName: "group.com.cocoajason.SwiftUIAndAppDemo")?.object(forKey: "userDefaults") as? String ?? "Default value"
Button(object) {
}
点击小组件菜单,打开宿主APP指定界面
1.主要代码
Link(destination: URL(string: "you app`s scheme") ?? URL(string: "you app`s scheme")!){
//View
}
widgetURL(<#T##url: URL?##URL?#>)
Link 用于给某个view赋予跳转连接,widgetURL用于给整个小组件添加跳转连接
2.在主工程AppDelegate.m中添加如下代码,由于使用小组件打开APP时,会执行如下代码,因此我们打印出小组件传过来的url,就可以在APP中跳转指定界面了。
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
[self printUrl:url];
return true;
}
- (void)printUrl:(NSURL *)url {
NSLog(@"%@", url);
}
3.编写试验代码
3.1. 先创建 CommonView.swift,可以用在不同组件中,其中放两个Text控件,其中一个显示home Page,一个显示Setting Page
3.1.1 普通link代码,其中Text有不同的连接地址
let homeLinkDestination = URL(string: "SwiftUIAndAppDemo://page=home")!
let settingLinkDestination = URL(string: "SwiftUIAndAppDemo://page=setting")!
struct CommonView: View {
var body: some View {
VStack {
Link(destination: homeLinkDestination, label: {
Text("Home Page")
})
Spacer()
Link(destination: settingLinkDestination, label: {
Text("Setting Page")
})
}
.padding()
}
}
3.2 我们为Extension_Two 创建三个不同的view,用于在不同尺寸下,展示不同的view
@Environment(\.widgetFamily) var family
var body: some View {
switch family {
case .systemSmall:
Extension_Two_SmallView()
case .systemMedium:
Extension_Two_MediumView()
default:
Extension_Two_LargeView()
}
}
3.3 分别编写三个不同view中的代码
3.3.1 SmallView
let smallWidgetUrl = URL(string: "SwiftUIAndAppDemo://widgetType=SmallView")!
struct Extension_Two_SmallView: View {
var body: some View {
VStack {
Text("Extension_Two_SmallView")
Spacer()
CommonView()
}
.widgetURL(smallWidgetUrl)
.padding()
}
}
3.3.2 MediumView
let mediumWidgetUrl = URL(string: "SwiftUIAndAppDemo://widgetType=MediumView")!
struct Extension_Two_MediumView: View {
var body: some View {
VStack {
Text("Extension_Two_MediumView")
Spacer()
CommonView()
}
.widgetURL(mediumWidgetUrl)
.padding()
}
}
3.3.3 LargeView
let largeWidgetUrl = URL(string: "SwiftUIAndAppDemo://widgetType=LargeView")!
struct Extension_Two_LargeView: View {
var body: some View {
VStack {
Text("Extension_Two_LargeView")
Spacer()
CommonView()
}
.widgetURL(largeWidgetUrl)
.padding()
}
}
3.3.4 分别打印上述三种view以及不同的点击位置如下
3.4 在组件中某个view后面添加WidgetUrl,为Text 添加WidgetUrl
Text("Setting Page")
.widgetURL(settingLinkDestination)
卡片类型 | 点击Home | 点击Setting | 点击空白 |
---|---|---|---|
small、medium、large | SwiftUIAndAppDemo://page=setting | SwiftUIAndAppDemo://page=setting | SwiftUIAndAppDemo://page=setting |
4.总结如下
·小尺寸的卡片,只能使用 widgetURL去处理跳转
·每个组件,只能处理一个Widget链接
·即不存在widgeturl也不存在link时,会直接打开APP,且APP不会执行openUrl方法
WidgetKit 桌面小组件-加载网络图片
当我们在APP中显示网络图片时,一般会使用KingFisher、SDWebImage、YYImage等图片加载框架,既能够下载网络图片,异步下载,又可以缓存到沙盒和内存。
但是小组件却不支持这一点,且小组件中无法使用UIKit控件。
因此我们需要在时间轴刷新时,就下载好所有图片,并且缓存到内存和沙盒中,然后在刷新时间轴,在刷新时间轴后,才能够从缓存中展示图片
调用图片加载框架,展示图片(事先已下载好图片)
Image(uiImage: WidgetImageLoader.shareLoader.getImage(itemModel.image, UIImage()))
.resizable()
.scaledToFit()
.cornerRadius(16)
.frame(width: 44, height: 44)
创建.Swift文件WidgetImageLoader.swift
import Foundation
import SwiftUI
enum WidgetError: Error {
case netError //网络请求出错
case dataError //数据解析错误
}
/*
由于不支持异步加载图片
所以暂时在网络请求好之后,直接下载好全部图片
使用NSCache暂存图片
*/
class WidgetImageLoader {
static var shareLoader = WidgetImageLoader()
private var cache = NSCache<NSURL, UIImage>()
/// 下载单张图片
/// - Parameters:
/// - imageUrl: 图片URL
/// - completion: 成功的回调
func downLoadImage(imageUrl: String?,completion: @escaping (Result<UIImage, WidgetError>) -> Void) {
if let imageUrl = imageUrl {
if let cacheImage = self.cache.object(forKey: NSURL(string: imageUrl)!) {
completion(.success(cacheImage))
} else {
URLSession.shared.dataTask(with: URL(string: imageUrl)!) { (data, response, error) in
if let data = data,
let image = UIImage(data: data) {
self.cache.setObject(image, forKey: NSURL(string: imageUrl)!)
completion(.success(image))
} else {
completion(.failure(WidgetError.netError))
}
}.resume()
}
} else {
completion(.failure(WidgetError.dataError))
}
}
/// 批量下载图片
/// - Parameters:
/// - imageAry: 图片数组集合
/// - placeHolder: 占位图,可传可不传
/// - completion: 成功回调
func downLoadImage(imageAry:[String],placeHolder:UIImage?,completion: @escaping (Result<[UIImage], WidgetError>) -> Void) {
let group:DispatchGroup = DispatchGroup()
var array = [UIImage]()
for image in imageAry {
group.enter()
self.downLoadImage(imageUrl: image) { result in
let image : UIImage
if case .success(let response) = result {
image = response
} else {
image = placeHolder ?? UIImage()
}
array.append(image)
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
completion(.success(array))
}
}
/// 获取image
/// - Parameters:
/// - imageUrl: 图片地址
/// - placeHolderImage: 占位图,请尽量传入
/// - Returns: 返回结果
func getImage(_ imageUrl:String, _ placeHolderImage:UIImage?) -> UIImage {
if let cacheImage = self.cache.object(forKey: NSURL(string: imageUrl)!) {
return cacheImage
} else {
if let cacheImag = placeHolderImage {
return cacheImag
} else {
return UIImage()
}
}
}
}
WidgetKit 桌面小组件-定位的问题
1.确保info.plist中有如下键值对
<key>NSWidgetWantsLocation</key>
<true/>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>我们要使用您的位置,为您推荐附近的优惠门店</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>我们要使用您的位置,为您推荐附近的优惠门店</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>我们要使用您的位置,为您推荐附近的优惠门店</string>
2.确保宿主APP开启使用时定位或者始终定位
3.小组件刷新时间大约为15分钟,且不允许长时间定位
区分黑暗模式
与尺寸类似,我们使用如下环境变量来取得当时的模式
@Environment(\.colorScheme) var colorScheme
switch self.colorScheme {
case .light:
Text("light")
case .dark:
Text("dark")
@unknown default:
Text("light")
}
卡片类型 | 对应尺寸 |
---|---|
light | 亮色模式 |
dark | 深色模式 |