Apple Watch share data
17 Mar 2015使用 NSUserDefaults
分享数据
首先我们要在创建的工程中打开应用和 WatchKit Extension 的 APP Groups
并且应用和 WatchKit Extension 要添加在同一个 group 下面。
然后我们创建一个数据对象,功能很简单 从
NSUserDefaults
中读取 String 数组 ,然后在对数组的添加删除操作后 更新 NSUserDefaults
对象
1 -(void)loadItems
2 _defaults =[[NSUserDefaults alloc] initWithSuiteName:@"group.com.test.DataSharing"];
3 _items = []_defaults objectForKey:@"Items"];
4 if (!_items)
5 _items =[NSMutableArray array];
6 }
7 }
8
9 -(void)appendWith:(NSString *)string
10 [_items addObject:string];
11 [self save];
12 }
13
14 -(void)removeItemAt:(NSInteger)index
15 [_items removeObjectAtIndex:index];
16 [self save];
17 }
18
19 -(void)save
20 [_defaults setObject:_items forKey:@"Items"];
21 [self.delege dataModelDidChanged];
22 }
在 WatchKit Extension 中 我们就可以使用同一个数据对象来更新 Watch app 的UI
1 -(void)loadTable
2 [self.tableView setNumberOfRows:[_dataModel.items count] withRowType:@"ItemCell"];
3 [_dataModel.items enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop)
4 WKRowItem *rowItem = [self.tableView rowControllerAtIndex:idx];
5 [rowItem.label setText:obj];
6 }];
7 }
Watch App 唤醒应用
因为我们在 Watch App 中也可以输入文本。所以在手表上更新数据后 我们还以通知 应用来使用新数据刷新UI。在 WKInterfaceController
有提供API 给我们
1 +(BOOL)openParentApplication:(NSDictionary *)userInfo
2 reply:(void(^)(NSDictionary *replyInfo, NSError *error)) reply;
1 [self presentTextInputControllerWithSuggestions:@[@"suggestion",@"Test",@"Input"]
2 allowedInputMode:WKTextInputModeAllowAnimatedEmoji
3 completion:^(NSArray *results)
4 __strong typeof(weakSelf) strongSelf = weakSelf;
5 if (strongSelf)
6 [_dataModel appendWith:results.firstObject];
7 [strongSelf loadTable];
8 [WKInterfaceController openParentApplication:@{@"update":@"update"}
9 reply:^(NSDictionary *replyInfo, NSError *error)}];
10 }
11 }];