运行 iOS 9.3 或更高版本的 iPhone 可以与多个运行 watchOS 2.2 或更高版本的 Apple Watch 配对。
iOS 上需要所有三个WCSessionDelegate 方法来支持快速手表切换所需的异步会话激活。
从手表切换:
启用自动切换后,当用户从一个 Apple Watch 切换到另一个 Apple Watch 时,iOS 应用会在切换过程中进入 inactive 和 deactivated 状态。 p>
移动到非活动状态使会话有少量时间来传递已接收到的任何数据。
// MARK: WCSessionDelegate - Asynchronous Activation
// The next 3 methods are required in order to support asynchronous session activation; required for quick watch switching.
func sessionDidBecomeInactive(session: WCSession) { // iOS only
/*
The session calls this method when it detects that the user has
switched to a different Apple Watch. While in the inactive state,
the session delivers any pending data to your delegate object and
prevents you from initiating any new data transfers. After the last
transfer finishes, the session moves to the deactivated state.
Use this method to update any private data structures that might be
affected by the impending change to the active Apple Watch. For example,
you might clean up data structures and close files related to
outgoing content.
*/
print("session did become inactive")
}
一旦传送了该数据,会话就会进入停用状态。此时,iOS 应用必须再次调用 activateSession 方法才能连接到新激活的手表。
func sessionDidDeactivate(session: WCSession) { // iOS only
print("session did deactivate")
/*
The session calls this method when there is no more pending data
to deliver to your app and the previous session can be formally closed.
iOS apps that process content delivered from their Watch Extension
should finish processing that content, then call activateSession()
to initiate a session with the new Apple Watch.
*/
// Begin the activation process for the new Apple Watch
WCSession.defaultSession().activateSession()
}
切换到手表:
iOS 和 watchOS 应用程序都将实现以下方法,以便在其 WCSession 激活后调用:
func session(session: WCSession, activationDidCompleteWithState activationState: WCSessionActivationState, error: NSError?) {
if let error = error {
print("session activation failed with error: \(error.localizedDescription)")
return
}
/*
Called when the activation of a session finishes. Your implementation
should check the value of the activationState parameter to see if
communication with the counterpart app is possible. When the state is
WCSessionActivationStateActivated, you may communicate normally with
the other app.
*/
print("session activated with state: \(activationState.rawValue)")
}
示例代码:
Apple 提供了QuickSwitch sample code 来演示如何正确使用 WatchConnectivity 框架,以支持通过多个 Apple Watch 进行快速手表切换。它使用updateApplicationContext 将指示符和颜色从配对的手表传递到手机。
其他说明:
未连接的手表应用可以继续使用包括交互式消息在内的所有传输方法(尽管传出数据确实会被系统排队,并且在用户切换回该手表之前不会传输)。
更多详情请见How can watchOS 2.2 app determine if its paired iPhone has switched to another Apple Watch?
致谢:
提供的代码基于 QuickSwitch,详细信息请参见支持与多个 Apple Watch 通信下的 WCSessionDelegate Protocol Reference 和 WCSession Class Reference。