我需要从userDefaults
Apple Watch 应用程序中获取一个数字以进行一些计算,我正在使用 WatchConnectivity 框架来获取这条信息,但我不喜欢我现在拥有它的方式是手机仅在加载 iPhone 应用程序 (viewDidLoad) 时将数据发送到 Watch,换句话说,我启动 Watch 应用程序需要打开 iPhone 应用程序才能将数据发送到 Apple Watch。
是否可以在 iPhone 不活动时从 iPhone 获取数据?
这是我正在使用的代码:
iOS 视图控制器
class ViewController: UIViewController, WCSessionDelegate {
var session: WCSession!
override func viewDidLoad() {
super.viewDidLoad()
if WCSession.isSupported() {
session = WCSession.default()
session.delegate = self
session.activate()
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState:WCSessionActivationState, error: Error?) {}
func sessionDidDeactivate(_ session: WCSession) { }
func sessionDidBecomeInactive(_ session: WCSession) { }
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
// Reply to watch with data from user defaults
replyHandler(["dataFromiPhone": readDoubleFromUserDefaults()])
}
}
WatchOS 接口控制器
class InterfaceController: WKInterfaceController, WCSessionDelegate{
var session: WCSession!
var myNumber:Double = 0
override func willActivate() {
super.willActivate()
if (WCSession.isSupported()) {
session = WCSession.default()
session.delegate = self
session.activate()
}
getDataFromiPhone()
}
override func didDeactivate() {
super.didDeactivate()
}
/// Delegate required method
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {}
func getDataFromiPhone(){
//Send Message to phone - I'm not sure if I need this message
let messageToSend = ["askiPhone":"Hi Phone, send me data from userDefaults."]
session.sendMessage(messageToSend, replyHandler: { replyMessage in
/// handle the reply
let dataFromPhone = replyMessage["dataFromiPhone"] as? String
DispatchQueue.main.async {
self.myNumber = Double(dataFromPhone!)!
}
}, errorHandler: {error in
/// catch any errors here
print("ERROR: \(error)")
})
}
}