How to share data between iPhone and Apple Watch using groups?

十年热恋 提交于 2019-12-07 10:03:47

问题


i am new to Watchkit development and unable to find solution to share data between iPhone and iWatch, please help me i am looking to share data using groups.


回答1:


We can pass the data between iPhone & iWatch using groups.

Basically iWatch can not do any processing and we need to share the data. We can share data using the NSUserDefaults.

But for that you need to enable Appp Groups from capabilities section in both your project target and your iwatch app target, as showed below

Below is the sample code to achieve that.

In your viewController or appDelegate file add following code

 NSUserDefaults *myDefaults = [[NSUserDefaults alloc]
                               initWithSuiteName:@"group.test.yourapp"];
[myDefaults setObject:@"aadil" forKey:@"name"];

Basically you are setting the value "aadil" for "name" variable.

Next step is to write code to retrieve that as below

 NSUserDefaults *myDefaults = [[NSUserDefaults alloc]
                               initWithSuiteName:@"group.test.yourapp"];
[myDefaults objectForKey:@"name"];

Hope this helps :)




回答2:


WARNING! It's not working with WatchOS 2 anymore, use methods from WatchConnectivity Framework. The best is updateApplicationContext: which always keep the latest data alive. From Apple doc:

Watch apps that shared data with their iOS apps using a shared group container must be redesigned to handle data differently. In watchOS 2, each process must manage its own copy of any shared data in the local container directory. For data that is actually shared and updated by both apps, this requires using the Watch Connectivity framework to move that data between them.



来源:https://stackoverflow.com/questions/28428614/how-to-share-data-between-iphone-and-apple-watch-using-groups

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