Search code examples
iosiphoneswiftwatchkitapple-watch

Move array from iPhone to AppleWatch programmatically


I want to pass the data from iPhone to AppleWatch. It means I want to use the array data from iPhone to AppleWatch. So, how can I move or use NSMutableArray from iPhone to AppleWatch programmatically?.


Solution

  • 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.