Jagat Dave Jagat Dave - 8 months ago 53
iOS Question

How can i transfer array from iPhone to AppleWatch programmatically

I want to pass the data from iPhone to

. It means I want to use the array data from iPhone to
. So, how can I move or use
from iPhone to

Answer Source

Watch OS1:

You can use NSUserDefault for this purpose. You need to create an app-group for this. To find your app groups: in In your main app, select your project in the project navigator and then select your main app target and choose the capabilities tab and switch on app groups.

And then you could do like this:

var myArr: [NSString] = [NSString]()
myArr.append("First value")
myArr.append("Second value")

// Save
NSUserDefaults(suiteName: "group.myapp.test")!.setObject(myArr, forKey: "myArray")
NSUserDefaults(suiteName: "group.myapp.test")!.synchronize()

// Read
if let testArray : AnyObject? = NSUserDefaults(suiteName: "group.myapp.test")!.objectForKey("myArray") {
   let readArray : [NSString] = testArray! as! [NSString]

Watch OS2:

If you want to save something from your phone to the NSUserDefaults on the Apple watch Target:

Use WatchConnectivity to send the data you want to save to the watch. Then when the watch receives the data you sent to it, save it to the Apple watch's default NSUserDefaults.

WCSession.defaultSession() will return the WCSession singleton for transfering data between your iOS and Watch app.

Here is a reference and guide for this.