实现功能:小组件和hostApp可以即时通信
前置条件
1 hostApp和WidgetExtension开启AppGroup 功能;
2 数据共享可以通过UserDefaults和FileManager两种形式。
问题
小组件和hostAPP怎么实现即时通信,比如app登陆的时候,小组件收到这条消息,更新自己的显示?
解决方式
1 不停的刷新小组件,3秒更新一次组件。❌
2 使用 CFNotificationCenter,app和widget通信。❌
3 使用一个公共的swift类,做通信交互。✅
第一种方法显然不行,因为小组件每天刷新的次数是有限制的,如果一开始刷新太频繁,可能每天后面小组件不再刷新。
第二种方式我在实践的时候出现了一些问题,后续会解释。
现在介绍第三种方式如下图:
在ViewController.m里面实现
- (void)loginIn {
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.my.com.test"];
[userDefaultssetObject:@"content"forKey:@"widget"];
[userDefaultssynchronize];
ViewUpdate *update = [[ViewUpdate alloc]init];
[updateupdateView];
}
在ViewUpdate.swift实现
importWidgetKit
class ViewUpdate: NSObject {
@objc public funcupdateView() -> () {
WidgetCenter.shared.reloadTimelines(ofKind: "MyWidget")
}
}
在widget.swift 获取数据
varname = UserDefaults.init(suiteName:"group.my.com.test")?.object(forKey:"widget")as!String?
if name==nil{
name ="登录" }
使用CFNotificationCenter 遇到的问题
问题描述:像使用NSNotificationCenter 一样使用CFNotificationCenter,hostApp在合适的时候发送消息,WidgetExtension接收消息。当我选择 widgetExtension为target 运行程序的时候,数据交互完全没有问题,但是当我以hostApp为target运行程序的时候,小组件收不到app发送的消息。当然打包之后安装的app,也是这样,小组件无法收到app发送的通知。
这个问题目前还没有解决。。。,后续再看
参考:https://www.jianshu.com/p/94a98c203763