0

I have a problem passing data from iOS to WatchOS 2.0

I want to send an ArrayList to WatchOS but my ArrayList has no type like String, Int but an Object that I generated.

    // here I fetch my Lists with Users
    var friendList: [UserProfile] = Utils().loadUsers("friendList")
    var blackList: [UserProfile] = Utils().loadUsers("blackList")
    var users: [UserProfile] = Utils().loadUsers("UsersList")

    // here I put the Lists in the Dictionary in order to send this Dictionary to Watch
    let dictionary: [String: AnyObject]=[
        "UsersList" : self.users,
        "BlackList" : self.blackList,
        "FriendList" : self.friendList
    ]

    WCSession.defaultSession().sendMessage(dictionary, replyHandler: { (data) -> Void in
        // handle the response from the device

        }) { (error) -> Void in
            print("error: \(error.localizedDescription)")
    }

In my WatchApp Class I try to get the Data but there is following error:

error: Payload contains unsupported type.

This is how I want to get the Data. If I send Bools, Integers or String this works, but not for Arrays like mine:

let userList: [UserProfile] = applicationContext["UsersList"] as! [UserProfile]
let blackList: [UserProfile] = applicationContext["BlackList"] as! [UserProfile]
let friendList: [UserProfile] = applicationContext["FriendList"] as! [UserProfile]

Hope anyone can help me with this Problem.

3
  • 1
    You can implement NSCoding in your class and then convert it to NSData and back using NSKeyedArchiver and NSKeyedUnarchiver and send the data
    – dan
    Jan 19, 2016 at 19:17
  • Thank you, i try that later! NSCoding is already implemented.
    – hannes
    Jan 20, 2016 at 8:22
  • That helped me, thanks!!
    – hannes
    Jan 21, 2016 at 16:08

4 Answers 4

3

Step 1: You need to have NSCoding properly working.

import Foundation

class UserProfile : NSObject, NSCoding {

    /// The name of the activity.
    var name: String

   /**
    The constructor

    :param: name The name of the user.
    */
    init(name: String, start: Int, end: Int) {
        self.name = name
    }

    required init(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObjectForKey("Name") as! String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(name, forKey: "Name")
    }
}

Step 2: Set the function that will be receiving your data:

func session(session: WCSession, didReceiveMessageData messageData: NSData, replyHandler: (NSData) -> Void) {

        // Set the same class to avoid the name change for every target.
        NSKeyedUnarchiver.setClass(UserProfile.self, forClassName: "UserProfile")

        // Unarchive the activity object passed from the paired device.
        guard let data = NSKeyedUnarchiver.unarchiveObjectWithData(messageData) else {
            return
        }

        let userProfiles = data as! [UserProfile]

        //Send the replyHandler you might need
        let response: NSData = //...
        replyHandler(response)
    }
}

Step 3: Set the function that will be sending your data:

        let userProfiles: [UserProfile] = //some of your UserProfiles...
        // Set the same class to avoid the name change for every target.
        NSKeyedArchiver.setClassName("UserProfile", forClass: UserProfile.self)

        // Archive the object to NSData.
        let data = NSKeyedArchiver.archivedDataWithRootObject(userProfiles)

        session.sendMessageData(data, replyHandler: { (data) -> Void in
            // handle the response from the device

            }) { (error) -> Void in
                print("error: \(error.localizedDescription)")
        }
1
  • probably better to be NSSecureCoding compliant rather than the "insecure" variant
    – ccjensen
    Jan 20, 2016 at 22:12
2

You are allowed to use any types that are allowed in property lists:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html

As NSString is one of those data types, you can use anything that can be serialized into Strings.

Example: you could serialize your objects into a JSON String, send it to the watch as a String and use JSON to create your objects from it. That's the way I chose.

1

UserProfile objects friendList, blackList, users are not serialised yet, and cannot be directly send to Apple Watch.

You can convert them to dictionaries before sending them to the Apple Watch.

1
  • I tried that too! It is a bit annoying but it works ;)
    – hannes
    Jan 21, 2016 at 16:10
1

Better to use UserDefaults if Watch is not updating the ArrayList of the user :-

enter image description here


You can share your "ArrayListObj" by enabling the Capabilites of group on both application and watch target and sharing by the Userdefaults among the Targets(iPhone and Watch).

//iPhone sharing Userinfo func sharedUserInfo() {

    if let userDefaults =  UserDefaults(suiteName: "group.watch.app.com" ) {
        userDefaults.set( UserProfileObj as AnyObject, forKey: "UserInfo")
        userDefaults.synchronize()
        }

    }

//Watch extracting the info

func sharedInfo() {
        if let userDefaults = UserDefaults(suiteName: "group.watch.app.com") {
            let userInfo = userDefaults.string(forKey: "UserInfo")
           }

       }
1
  • AFAIK, this is no longer supported in WatchOS 2 even though it is still in the documentation.
    – Bms270
    Aug 12, 2017 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.