我使用WatchConnectivity将简单的字典从iPhone发送到Apple。
在Apple方面,为了避免在打开应用程序时上下文可能没有排队的事实,将最后接收到的数据保存到UserDefaults中,如果在设置WatchKit表时队列中没有任何内容,则将其检索。我已经在另一个WatchKit应用程序中实现了这一点,一切都运行得很好,但是在这个应用程序中,手表从来没有接收过数据。
我只在模拟器上试过,因为我的应用程序在我的手表上旋转了很长时间,从来不加载(加载屏幕看起来像一个监视系统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
}发布于 2016-01-02 00:50:08
更改这一行:
[[WCSession defaultSession] updateApplicationContext:toPass error:nil];将是:
NSError *error = nil;
If (![[WCSession defaultSession] updateApplicationContext:toPass error:&error]) {
NSLog(@"error: %@", error);
}我打赌你会看到你得到了一个错误的回报!
另外,AppDelegate.profiles包含什么类型的对象?
https://stackoverflow.com/questions/34559758
复制相似问题