登录开发者账号
https://developer.apple.com/account/ios/certificate/development
// 配置证书
Description :描述
Identifier:Groups.com.XXXX
工程添加widget类 如下图
选择 NEXT
填好 Product Name 文件名
选择 Finish 创建好了
- (void)viewDidLoad {
[superviewDidLoad];
// 打开时的高度
self.preferredContentSize =CGSizeMake([UIScreenmainScreen].bounds.size.width,100);
}
// 折叠
- (void)viewWillAppear:(BOOL)animated {
[superviewWillAppear:animated];
self.extensionContext.widgetLargestAvailableDisplayMode =NCWidgetDisplayModeExpanded;
}
//展开
- (void)widgetActiveDisplayModeDidChange:(NCWidgetDisplayMode)activeDisplayMode withMaximumSize:(CGSize)maxSize {
if (activeDisplayMode ==NCWidgetDisplayModeCompact) {
self.preferredContentSize =CGSizeMake([UIScreenmainScreen].bounds.size.width,110);
} else {
self.preferredContentSize =CGSizeMake([UIScreenmainScreen].bounds.size.width,300);
}
}
- (UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets:(UIEdgeInsets)defaultMarginInsets{
return UIEdgeInsetsMake(0.0,0.0,0,0);
}
//通过extensionContext借助host app调起APP (比如放个按钮 在按钮点击事件里直接调用以下方法 打开APP)
- (void)openURLContainingAPP {
[self.extensionContextopenURL:[NSURLURLWithString:@"appextension://xxx"]completionHandler:^(BOOL success) {
if (success) {
NSLog(@"APP启动完成");
};
}];
}
// 设置 extensionContext项目->TARGETS->右侧顶部选info标签拉到最底部-> URL Types 里面进行设置->URL Schemes 里面写的与appextension://要一致就可唤起APP
// 数据传递 共享 问题 (我的选的 NSUserdefaults 因为我传的数据量不大)
首先们选择targets->然后选择containing app->Capabilities->打开app groups的开关->打开选+ 写 group.com.xxx
通过后项目会生成 (Widget的名字).entitlements的文件可以看到
注意:你的项目与Widget的两个地方的 app groups都要设置且必须一致才能保障正常通信 widget默认不支持任何第三方类、库的需要单独设置
// 存数据
- (void)saveDataByNSUserDefaults{
NSUserDefaults *shared = [[NSUserDefaultsalloc]initWithSuiteName:@"group.com.xxx"];
[sharedsetObject:@"asdfasdf"forKey:@"widget"];
[shared synchronize];
}
// 读数据
- (NSString *)readDataFromNSUserDefaults{
NSUserDefaults *shared = [[NSUserDefaultsalloc]initWithSuiteName:@"group.com.xxx"];
NSString *value = [sharedvalueForKey:@"widget"];
return value;
}