我正在使用 WatchConnectivity 将一个简单的字典从 iPhone 发送到 Apple Watch。
在 Apple Watch 方面,为了解决打开应用程序时上下文可能不会排队的事实,最后接收到的数据将保存到 UserDefaults 并在设置我的 WatchKit 表时在队列中没有任何内容时检索。我已经在另一个 WatchKit 应用程序中实现了这一点,一切都运行得很好,但是在这一个数据中,Watch 永远不会接收到数据。
我只在模拟器中尝试过,因为我的应用程序在我的手表上永远旋转并且永远不会加载(加载屏幕看起来像 WatchOs 1 屏幕?)。WatchConnectivity 框架包含在每个产品(扩展程序和 iPhone 应用程序)中。谢谢你的帮助。
这是 iPhone 代码(在 ViewController 中实现):
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
}
- (void)viewDidAppear:(BOOL)animated {
NSDictionary *toPass = [[NSDictionary alloc] initWithObjectsAndKeys:AppDelegate.profiles,@"profiles", nil];
[[WCSession defaultSession] updateApplicationContext:toPass error:nil];
NSLog(@"sent data");
[self.tableView reloadData];
}
苹果手表代码:
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
// Configure interface objects here.
self.profiles = [[NSMutableArray alloc] init];
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
[self setupTable];
}
- (void)session:(WCSession *)session didReceiveApplicationContext:(NSDictionary<NSString *,id> *)applicationContext {
NSDictionary *receieved = [[NSDictionary alloc] init];
receieved = applicationContext;
NSMutableArray *profiles = [[NSMutableArray alloc] init];
profiles = [receieved objectForKey:@"profiles"];
self.profiles = [[NSMutableArray alloc] init];
self.profiles = profiles;
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:self.profiles];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arrayData forKey:@"bookmarks"];
[self setupTable];
NSLog(@"new");
}
- (void)setupTable {
...
After some setup code
if (self.profiles.count == 0) {
NSLog(@"Nothing in the queue, checking defaults");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *got = [defaults objectForKey:@"bookmarks"];
NSLog(@"Got Defaults!");
self.profiles = [[NSMutableArray alloc] init];
self.profiles = [NSKeyedUnarchiver unarchiveObjectWithData:got];
}
...
More setup code later
}