问题
I have an iPhone and an Apple Watch paired together, and there are some values stored in the user defaults of the phone. I want my Apple Watch to be able to retrieve that stored information somehow and bring it back to the Watch. What is the best method of achieving this with Swift?
回答1:
Since watchOS2
, you don't have any built in function for communicating between the iOS and watchOS app other than the WatchConnectivity
framework. Due to the fact that Watch apps are no longer considered App Extensions, they don't have access to AppGroups
and hence to UserDefaults
on the iPhone.
For syncing UserDefaults
, the updateApplicationContext(_:) function seems to be the best solution. You can send a dictionary of data with this function (the data you just saved to UserDefaults
on the iPhone) and the system tries to make sure that the data is received by the time your app is displayed to the user. If the function is called several times before the app would be visible to the user (run in the foreground), the system overwrites the previous data, so the Watch app only receives the most recent data to display.
来源:https://stackoverflow.com/questions/44856215/retrieve-user-defaults-information-from-an-apple-watch