简体   繁体   中英

Send String from iPhone to WatchKit App

I'm trying to share a string from my iPhone app to my WatchKit app. I have enabled App Groups for both the iOS app and the WatchKit extension. Then, in my iOS app, I set a variable for the UserDefaults...

let defaults = UserDefaults(suiteName: "group.com.jacobcavin.appName")

Then in the ViewController , I set defaults to a string from the text of a TextField...

defaults?.set(textField.text!, forKey: "KEY")

Inside of the iOS app, this works perfectly and I can access this and get the right value. But, inside the WatchKit app, I try to get the string...

let defaults = UserDefaults(suiteName: "group.com.jacobcavin.appName")
let string = defaults?.string(forKey: "KEY")

But string returns nil . I've looked through tons of tutorials, and I have made sure that each target has the same group identifier, different Bundle Identifiers, and the entitlement.plist files are correct. Can you please help?

A UserDefaults app group does not work with a watch app extension. You need to use WCSession send an applicationContext to the watch and then in the watch set those values to its UserDefaults .

For example on the iPhone you would activate the WCSession.default and call try WCSession.default.updateApplicationContext(applicationContext) where applicationContext is [String : Any] . The application context will be sent to the watch if the extension is in the foreground or will be delivered to the extension the next time the app is launched.

To respond to the context in the watch app extension, activate the default session declare yourself as a delegate to receive the new application context:

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        // handle receiving application context
        DispatchQueue.main.async
        {
            // Save to UserDefaults or Update UI etc.
        }
}

A somewhat dated example can be found here . The process is still the same but the code has not been updated.

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