iOS 插件开发之 today widget

作者: StarHuiDream | 来源:发表于2017-03-09 17:07 被阅读555次

    Dmo链接

    一、什么是today widget

    苹果官方关于 today widget 的介绍(点击链接查看详情)

     App extensions in the Today view are called widgets. Widgets give users quick access to information that’s important right now. For example, users open the Today view to check current stock prices or weather conditions, see today’s schedule, or perform a quick task such as marking an item as done. Users tend to open the Today view frequently, and they expect the information they’re interested in to be instantly available.

    A Today widget can appear on the lock screen of an iOS device if the user has enabled this. They do so in the “Allow Access When Locked” area by going to Settings > Touch ID & Passcode > Notifications View.

          今日视图中的 app扩展叫做widget ,widget 可以为用户提供当前所需简明扼要的信息 ,例如用户打开今日查看股票价格或者天气状况,今天的日程表,待办事等等。用户趋向于频繁的打开widget 以便获取最新的重要的信息。同时用户能够设置中是否允许  today widget  在锁屏上出现,。

    二、创建一个带today widget 的工程

    打开一个已经创建好的程序,选择File>New>Target> Today Extension    操作如下图      图2-1  图2-2

    图2-1 图2-2

    创建完成之后,我们可以在工程里面看到这几个文件。

    创建完成之后

          today widget 插件是依靠于宿主程序存在的,宿主程序就是普通创建的程序。

    三、today widget插件和宿主程序之间的数据共享

    苹果官方关于插件和宿主程序之常见场景的处理文档

    Sharing Data with Your Containing App

    Even though an app extension bundle is nested within its containing app’s bundle, the running app extension and containing app have no direct access to each other’s containers.

    You can, however, enable data sharing. For example, you might want to allow your app extension and its containing app to share a single large set of data, such as prerendered assets.

    To enable data sharing, use Xcode or the Developer portal to enable app groups for the containing app and its contained app extensions. Next, register the app group in the portal and specify the app group to use in the containing app. To learn about working with app groups, seeAdding an App to an App Group.

    After you enable app groups, an app extension and its containing app can both use theNSUserDefaultsAPI to share access to user preferences. To enable this sharing, use theinitWithSuiteName:method to instantiate a new NSUserDefaultsobject, passing in the identifier of the shared group. For example, a Share extension might update the user’s most recently used sharing account, using code like this:

    // Create and share access to an NSUserDefaults object

    NSUserDefaults *mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName: @"com.example.domain.MyShareExtension"];

    // Use the shared user defaults object to update the user's account

    [mySharedDefaults setObject:theAccountName forKey:@"lastAccountName"];

        虽然扩展程序的包是依赖于宿主程序的包存在的,但是扩展程序是不能直接访问宿主程序的沙盒。

        但是你仍然可以,通过开启 宿主程序的 appGroup 来使宿主程序和扩展程序之间完成数据共享。当你开启app group 之后扩展程序和宿主程序可以使用NSUserDefaults  的initWithSuiteName方法来存储数据。

    例如 :NSUserDefaults *mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName: @"com.example.domain.MyShareExtension"];

    [mySharedDefaults setObject:theAccountName forKey:@"lastAccountName"];

    给宿主app设置appGroup 的方法如下图 3-1 所示

    图 3-1

    然后点击加加号在弹出框里面输入appGroup 的名字。如下图3-2

    图3-2

    添加完成之后如下图3-3

    图3-3

    然后打开插件的appGroup 如下图 图3-4

    图3-4

    创建完成之后,我们就可以将数据存入appGroup中,方便插件和宿主程序共享。在本次示例中,我将采用对象归档,解档的方式将数据缓存到本地,数据模型在实现<NSCoding>协议之后可以通过如下的方法将数据缓存到本地

    NSURL*mURL = [[NSFileManagerdefaultManager] containerURLForSecurityApplicationGroupIdentifier:@"appGroup 的名称 (如上面的 "group.STTodyaWidget.data")"];

    mURL = [mURL URLByAppendingPathComponent:@"保存的名称"];

    Bool  isSaveSuccess = ([NSKeyedArchiver archiveRootObject:xxxmodel toFile:mURL.path]&& result);

    从本地取出数据

    XXXModel   *xxxmodel =[NSKeyedUnarchiver unarchiveObjectWithFile:mURL.path];

    由于插件和宿主app 是两个相互独立的程序,所以,在插件中是不能直接访问宿主程序的类,如果要创建一个插件和宿主程序都要使用的类可以勾选下面的勾选框如图3-5

    图3-5

    如果插件需要用到宿主程序里面之前建好的类的话,只需要,选中类将下图中的勾选框勾选上就可以了如下图 图3-6

    图3-6

    四、today widget插件的布局

    Because user interaction with Today widgets is quick and limited, you should design a simple, streamlined UI that highlights the information users are interested in. In general, it’s a good idea to limit the number of interactive items in a widget. In particular, note that iOS widgets don’t support keyboard entry.

    NOTE:

    Avoid putting a scroll view inside a Today widget. It’s difficult for users to scroll within a widget without inadvertently scrolling the Today view.

    iOS.Because Today widgets don’t allow keyboard entry, users need to be able to use the containing app to configure a widget’s content and behavior. In the Stocks widget, for example, users can switch between different representations of a symbol’s value, but they must open the Stocks app to manage the list of symbols.

    today widget  的设计应该遵从能够以简洁的界面为用户提供高质量的信息的原则,today widget 不允许键盘的弹出。尽量不要将scrollview 放到widget 上因为用户很难在这个页面进行滑动。

     4.1 使用sb

    我们在创建完today widget 之后,Xcode 会为我们创建好MainInterface.storyboard。我们可以使storyboard 来进行布局。如下图 图4-1

    图4-1

    运行效果如下 图4-2

    图4-2

     在viewDidLoad中添加这段代码可以使用折叠效果

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {

    self.extensionContext.widgetLargestAvailableDisplayMode = NCWidgetDisplayModeExpanded;

    }

    然后实现代理方法

    - (void)widgetActiveDisplayModeDidChange:(NCWidgetDisplayMode)activeDisplayMode withMaximumSize:(CGSize)maxSize

    {

    if (activeDisplayMode == NCWidgetDisplayModeCompact) {

    self.preferredContentSize = maxSize;

    } else if (activeDisplayMode == NCWidgetDisplayModeExpanded) {

    CGFloat height = 你要设置的展开时候的高度;

    self.preferredContentSize = CGSizeMake(0,height );

    }

    }

    展开折叠效果

    如果在10以下的系统我们需要在-(void)viewWillAppear:(BOOL)animated;里面设置today widget 的高度。

    if (stsystemVersion < 10.0) {

    CGFloat height = self.eventListModel.eventList.count * cellH ;

    height        = height > cellH ? height : cellH;

    [self setPreferredContentSize:CGSizeMake(0, height+ 30)];

    }

    如果你想设置today widget 的内边距可以在这个代理方法中设置

    - (UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets:(UIEdgeInsets)defaultMarginInsets

    {

    return  UIEdgeInsetsMake(0, 40, 0, 0);

    //    return UIEdgeInsetsZero;

    }

     4.2使用纯代码

    五、today widget跳转到宿主程序

    打开宿主程序的 plist 文件 添加URL types 如下图

    然后在today widget 中添加这段代码,然后就可以从widget跳转到宿主程序

    [self.extensionContext openURL:[NSURL URLWithString:@"STTodayWidget://GOTOEventListVC"] completionHandler:^(BOOL success) {

    NSLog(@"open url result:%d", success);

    }];

    在appdelegate 中添加下面的方法

    // 9.0 以后

    - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options {

    }

    // 9.0 以前

    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    }

    六、today widget的网络请求

    七、today widget的国际化

    八、today widget的打包上线

    Demo链接

    相关文章

      网友评论

      • 小番茄阳阳:怎么调用项目里面的网络请求工具
        StarHuiDream:将所用到的文件引入到widget,方法可以参照 https://www.jianshu.com/p/9704cfabc753 里面的widget 的国际化。 或者你可看看 https://www.jianshu.com/p/0ea65dd380ab 这片文章 里面的 widget工程使用宿主工程中的类文件。
      • 菊上一枝梅:棒棒棒👍
      • 扑倒的柔情:请问一下 widget的国家化怎么做
        StarHuiDream:你好,我这两天写了一个关于国际化处理的博客,里面讲解到widget 的国际化处理
        http://www.jianshu.com/p/9704cfabc753。希望能帮到你。

      本文标题:iOS 插件开发之 today widget

      本文链接:https://www.haomeiwen.com/subject/ewyygttx.html