升级到XCode 8后,我的应用更新被拒绝了,因为监视应用中的按钮对iOS应用没有影响。在模拟器中重新运行,似乎通过WCSession发送消息偶尔在一台机器上没有错误而失败,而且几乎总是在我使用的另一台机器上。
我创建了一个简单的应用程序,可以在iOS和监视应用程序中使用按钮和计数器复制行为。目的是点击iOS应用程序中的按钮将增加手表应用程序中的计数器,反之亦然。
有几次,当我离开应用程序运行一段时间后,消息最终被传递(大约2分钟后)。
iOS App ViewController:
class ViewController: UIViewController, WCSessionDelegate {
var count: Int = 0
var watchSession: WCSession?
@IBOutlet var countLabel: UILabel?
@IBAction func sendMessage(sender: AnyObject) {
watchSession?.sendMessage(
["message":"increment"],
replyHandler: { (message: [String : Any]) in
},
errorHandler: { (err: Error) in
})
}
override func viewDidLoad() {
super.viewDidLoad()
if(WCSession.isSupported()){
watchSession = WCSession.default()
watchSession!.delegate = self
watchSession!.activate()
}
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
count+=1
updateView()
replyHandler([:])
}
func updateView(){
DispatchQueue.main.async {
self.countLabel?.text = ("\(self.count)")
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {}
func sessionDidBecomeInactive(_ session: WCSession){}
func sessionDidDeactivate(_ session: WCSession){}
}
watchOS InterfaceController:
class InterfaceController: WKInterfaceController, WCSessionDelegate {
var count: Int = 0
var watchSession : WCSession?
@IBOutlet var countLabel: WKInterfaceLabel?
@IBAction func sendMessage(sender: AnyObject) {
watchSession?.sendMessage(
["message":"increment"],
replyHandler: { (message: [String : Any]) in
},
errorHandler: { (err: Error) in
})
}
override func willActivate() {
super.willActivate()
if(WCSession.isSupported()){
watchSession = WCSession.default()
watchSession!.delegate = self
watchSession!.activate()
}
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
count+=1
updateView()
replyHandler([:])
}
func updateView(){
countLabel?.setText("\(self.count)")
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {}
}