How to send data from Iphone to Watchkit in OS2 in

2019-04-08 01:58发布

问题:

I want to send a dictionary from iPhone to Watchkit in watchOS 2.

In watchOS 1 it works fine for me with appgroups but in watchOS 2 I know that we have to use WCSession but I don't know how to use it.

Please help me find the solution.

回答1:

This blog post should help you out.

From that post: First, you'll create and activate a WCSession like so:

if (WCSession.isSupported()) {
    let session = WCSession.defaultSession()
    session.delegate = self
    session.activateSession()
}

For transferring a dictionary:

let applicationDict = // Create a dict of application data
let transfer = WCSession.defaultSession().transferUserInfo(applicationDict)

Then, on the receiving end, you'll need to implement session:didReceiveUserInfo: (Developer documentation). Note, according to Apple's "watchOS2 Transition Guide,"

To begin communication, both your Watch app and your iOS app must have an active WCSession object. Typically, each app creates, configures, and activates a session object at launch time and stores a reference to it in a central location. When you want to send data, you retrieve the session object and call its methods.