WatchConnectivity不发送数据

时间:2016-01-01 20:29:21

标签: ios objective-c watchkit apple-watch watchconnectivity

我正在使用WatchConnectivity将简单的字典从iPhone发送到Apple Watch。

在Apple Watch方面,为了解决在打开应用程序时上下文可能没有排队的事实,如果在设置WatchKit表时队列中没有任何内容,则最后收到的数据将保存到UserDefaults并进行检索。我已经在另一个WatchKit应用程序中实现了这一点,一切都运行得很好,但在这一个数据从未被Watch接收。

我只是在模拟器中尝试过,因为我的应用程序在我的手表上永久旋转并且从不加载(加载屏幕看起来像WatchOs 1屏幕?)。 WatchConnectivity框架包含在每个产品中(Extension和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];
}

Apple Watch Code:

- (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
}

1 个答案:

答案 0 :(得分:0)

更改此行:

[[WCSession defaultSession] updateApplicationContext:toPass error:nil];

成为:

NSError *error = nil;
If (![[WCSession defaultSession] updateApplicationContext:toPass error:&error]) {
    NSLog(@"error: %@", error);
}

我打赌你会发现你的错误已经退回了!

此外,AppDelegate.profiles包含哪种类型的对象?