Communicating Updates between iPhone and Watch wit

2019-03-02 20:08发布

问题:

I have a shared core data backing my iPhone app and WatchKit Extension. They both function well independently, but I'm worried about concurrent use.

In the Extension, I have a UITableView that has an array of data. Right now it just grabs that array from the shared core data during -awakeWithContext.

I want to have some sort of communication between the app and extension when a record is created/updated/deleted so that it can be duplicated on the other side immediately (instead of on the next query to Core Data).

This question, How to send data from iphone to watchkit in swift, goes into the iPhone having a handler for when something happens in the Watch, but I'm more concerned about it going the other way. Right now all I can think of is querying core data pretty often to take care of it.

回答1:

A very common solution and one of the only ways is to use MMWormhole.

MMWormhole uses the CFNotificationCenter to communicate changes instantaneously across the app and the extension, passing information through shared application groups.

Example of passing data through from the MMWormhole GitHub README:

// Sender (Watch Extension)
[self.wormhole passMessageObject:@{@"buttonNumber" : @(1)} identifier:@"button"];

// Receiver (Phone)
[self.wormhole listenForMessageWithIdentifier:@"button" 
  listener:^(id messageObject) {
    self.numberLabel.text = [messageObject[@"buttonNumber"] stringValue];
}];


回答2:

There are different ways.

  1. You can use MMWormhole
  2. If you do not like to use a third-party library, you may use Darwin notifications directly. A good tutorial is already available on stackoverflow.