在Apple Watch上未调用session(_:activationDidCompleteWith:error:)(但在Simulator中调用了)

时间:2018-12-09 14:06:48

标签: ios swift watchkit watchconnectivity

我创建了一个简单的swift类:

true

在我的Watch App Extension中,我加载了创建此类的实例

import Foundation
import WatchConnectivity

class WatchCommunication : NSObject, WCSessionDelegate {

    var session: WCSession!

    override init() {
        super.init()

        if WCSession.isSupported() {
            print("WCSession is supported")
            self.session = WCSession.default
            self.session.delegate = self
            if session.activationState == WCSessionActivationState.activated {
                print("activationState is activated")
            } else {
                print("activationState is not activated")
                self.session.activate()
            }
        } else {
            print("WCSession is not supported")
        }
    }

    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        print("activationState", activationState.rawValue)
        print(error)
    }
}

当我在模拟器中测试此代码时,我看到了以下记录

class ExtensionDelegate: NSObject, WKExtensionDelegate {

    let watchCommunication: WatchCommunication = WatchCommunication() 

    // ...

一切正常。 当我在测试的iPhone X上运行相同的应用程序并配对了Apple Watch 3时,日志将显示

 WCSession is supported
 activationState is not activated
 activationState 2
 nil

所以看来方法

 WCSession is supported
 activationState is not activated

Apple Watch上从未调用过它。

类似

的方法
 func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {

也不会在设备上调用(但正在模拟器上运行)。

在iPhone X方面,调用 func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) { 方法,其中actionDidCompleteWith 2(activationState)和activated不会引发错误。

但是,iPhone和Apple Watch之间存在通信,因为方法https://developer.apple.com/documentation/healthkit/hkhealthstore/1648358-startwatchapp确实确实在手表上开始锻炼(并且所有Apple和第三方手表应用程序都正常工作)。

1 个答案:

答案 0 :(得分:-1)

进一步的参考:

重新启动Apple Watch(我从不执行其他操作)确实解决了该问题...