WatchConnectivity how to share session among multiple WKInterfaceControllers?

拥有回忆 提交于 2020-01-06 20:12:48

问题


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.



来源:https://stackoverflow.com/questions/38391480/watchconnectivity-how-to-share-session-among-multiple-wkinterfacecontrollers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!