iOS Widget 开发2

3,979 阅读2分钟

「这是我参与2022首次更文挑战的第12天,活动详情查看:2022首次更文挑战」。

NSFileManager
//写
NSError *err = nil;
NSURL *url = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"你的App Group"];
url = [url URLByAppendingPathComponent:@"Library/Caches/ widget"];
NSString *str = @"hahahaha";
BOOL result = [str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (!result)
{
    NSLog(@"%@",err);
}
else
{
    NSLog(@"save:%@ success.",str);
}
//读
NSError *err = nil;
NSURL *url = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"你的App Group"];
url = [url URLByAppendingPathComponent:@"Library/Caches/ widget"];
NSString *str = [NSString stringWithContentsOfURL:url encoding: NSUTF8StringEncoding error:&err];

这样你就可以在app和widget里共享数据了。

通知通信
  • 再来说一下另外一种交互。比如Widget上点击了按钮,app内实时变化。这种情况就不是数据共享可以搞定的了。这里你需要用到CFNotificationCenter。(NSNotificationCenter,KVO,Delegate不要试了没用)代码如下:
static ViewController *vc = nil;

// 发送通知
- (void)postNotificaiton
{
    CFStringRef keys[1];
    keys[0] = CFSTR("wiwi");
    CFStringRef values[1];
    values[0] = CFSTR("90");
    CFDictionaryRef dic = CFDictionaryCreate(NULL, (void*)keys,(void*)values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();
    CFNotificationCenterPostNotification(notification, CFSTR("widgetNoti"), NULL, dic, YES);
    
}
// 添加监听
- (void)addObserver
{
    //适当的地方赋值就行
    vc=self
    CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();
    CFNotificationCenterAddObserver(notification, (__bridge const void *)(self), observerMethod, CFSTR("widgetNoti"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
}

void observerMethod (CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    NSDictionary  *nsdic = (__bridge_transfer  NSDictionary*)userInfo;
    //拿到传的值后调控制器的方法做刷新
    [vc method:nsdic];
}
// 移除监听
- (void)removeObserver
{
    CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter ();
    CFNotificationCenterRemoveObserver(notification, (__bridge const void *)(self), CFSTR("widgetNoti"), NULL);
}

看起来很流畅,结果确实值根本传不过来,尴尬了。看一下官方文档说的就是If center is a Darwin notification center, this value is ignored.
但是这也问题不大,能收到通知就行,可以通过App Group来拿数据。当然你也可以用第三方库来做,MMWormhole ,也是基于CFNotificationCenter这个来的。

代码共享等等
  • 如果你要让主app里的文件,Widget 也能用,很简单。将文件的target membership 勾选widget工程就行了。

image.png

  • 如果你要使用pod,在podfile里多加个target就行了
target 'WidgetDD' do

end

注意你的Configurations 和Link Binary(不过一般应该自动就设置好了)

image.png

image.png

  • 如果你要做Widget 多语言,一样的,把多语言文件target membership勾一下,把主app里的多语言配置文件分享出来就可以了。

差不多就是这写这么多了,这东西记得尽量呈现功能比较简单的,交互性不强的东西哟,毕竟是一个小的扩展程序。(不知道漏了什么没有,漏了以后再加, 赫赫)。