简体   繁体   中英

How to Share data between iPhone app and applewatch?

I have a problem regarding share data from iPhone app to apple watch. I have try below code to share NSMutablearray to apple watch but its not working.

NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:arrStartScore];
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.test.StartScore"];
[defaults setObject:encodedObject forKey:@"WatchHomeViewTableList"];
[defaults synchronize];

For Retrieve Data to apple watch

NSUserDefaults *myDefaults = [[NSUserDefaults alloc]                                 initWithSuiteName:@"group.com.test.StartScoreCheck"];

arrStartScore = [myDefaults objectForKey:@"WatchHomeViewTableList"];
NSLog(@"dict....%@",arrStartScore);

To send data from phone to watch, use this code.

WCSession *session = [WCSession defaultSession];
NSError *error;

[session updateApplicationContext:@{@"message": yourArray} error:&error];

To receive data from phone on the watch:

 - (void) session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,NSMutableArray *> *)applicationContext {   
 }

you can access your array in didReceiveApplicationContext using

  [applicationContext objectForKey:@"message"];

watchOS3 have separated UserDefaults on watch and phone. AppGroups are can share data among one developer's applications within one device. In order to transfer data between devices, use WatchConnectivity framework.

Documentation

You can share data using WatchKit Connectivity Framework. There are different ways you can use for background or interactive.

Check this video by apple it explains all the different ways to communicate between iPhone and Watch.

Also, you can create a singleton class of watch connectivity and use it in both iOS and WatchOS. Establish the session in both the device and integrate the delegate methods and you are done. You can now send and receive messages to and fro from iOS and WatchOS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM