I have a situation where I need to share WCSession among multiple WKInterfaceControllers. Singleton approach won't work, once you set delegate to a class, all delegates in the other classes are invalidated. Scenario: interface A send and receive data, based on the data content, present interface B. Tap on interface B, will request and receive additional data. How would you share the WCSession between A and B ?
问题:
回答1:
The other answer doesn't explain that an app-wide session would work.
You can use an app-wide WCSession
singleton which would be available to all your interface controllers. You simply instantiate a session manager very early in the app life cycle, and let it be its own delegate.
Instead of trying to make each interface controller handle the session delegation (which won't work well), a session manager (singleton) can handle all the transfers for your interface controllers.
As mentioned in the other answer, you could then use notifications to let interested interface controllers know when their new data arrives.
Using a modular approach, such as a session or data manager, helps to keep such code out of a controller, where it really doesn't belong. It also makes it easier to test and utilize each module.
I won't repeat the code here, as there have already been several existing answers posted on Stack Overflow, as well as articles on the web, which cover this technique in detail. For example:
Using WCSession with more than one ViewController
WatchConnectivity: Say Hello to WCSession
You'll often find these types of answers within narrower questions that ask how to share data between, say, a watch app and its complication controller.
回答2:
Use NSNotification and listen for changes in all view controllers.