iOS的Extension Widget开发

1 、初始化Today Extension项目

  • 新建项目

image

image

  • 布局方式

storeyboard布局

MainInterface.storeybord

image

纯代码编写

需要配置info.plist的俩项参数移除NSExtensionMainStoryboard键,并添加NSExtensionPrincipalClass键,使用view controller的名字作为值。

image

  • 折叠功能
      - (void)viewWillAppear:(BOOL)animated { 
                  [super viewWillAppear:animated];
                  self.extensionContext.widgetLargestAvailableDisplayMode = 
          NCWidgetDisplayModeExpanded;
          }
    
  • 隐藏Today Extension
      NCWidgetController *widgetController = [NCWidgetController widgetController];
      [widgetController setHasContent:NO forWidgetWithBundleIdentifier:@"扩展的id"];
    
  • NCWidgetProviding代理

折叠代理

    - (void)widgetActiveDisplayModeDidChange:(NCWidgetDisplayMode)activeDisplayMode withMaximumSize:(CGSize)maxSize {
    if (activeDisplayMode == NCWidgetDisplayModeCompact){ 
    self.preferredContentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 110); 
    } 
    else { 
    self.preferredContentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 300); 
    }
    }

缩进

    - (UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets: (UIEdgeInsets)defaultMarginInsets {
    return UIEdgeInsetsZero;
    }

刷新Today Extension页面

    - (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
    // Perform any setup necessary in order to update the view.
    // If an error is encountered, use NCUpdateResultFailed
    // If there's no update required, use NCUpdateResultNoData
    // If there's an update, use NCUpdateResultNewData
    completionHandler(NCUpdateResultNewData);
    }

2 、 与APP交互

  • 跳转APP

APP设置URL Schemes

image

Today Extension实现跳转

    - (void)jumpHomeAppEvents {
        NSString *schemeString = @"demo://";
        [self.extensionContext openURL:[NSURL URLWithString:schemeString] completionHandler:^(BOOL success) {
        }];
    }

3 、 与APP共享数据

  • 创建APPGroups

登录appdeveloper网站创建APPGroups

image

image

Xcode设置APPGroups

image

APP存储数据

    - (void)saveDataByNSUserDefaults{
        NSUserDefaults* userDefault = [[NSUserDefaults alloc] initWithSuiteName:@"group.listennba.appGroup"];
        [userDefault setValue:@"你好,通知栏扩展" forKey:@"haha"];
    }

Today Extension读取数据

    - (void)readDataFromNSUserDefaults{
        NSUserDefaults * userDefault = [[NSUserDefaults alloc] initWithSuiteName:@"group.listennba.appGroup"];
        NSLog(@"读取出的数据为:%@",[myDefaults objectForKey:@"haha"]);
    }

实例

image

image



本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!