如何将带有 transferUserInfo 的字典传输到 Apple Watch?

How do I transfer a dictionary with transferUserInfo to Apple Watch?

我正在尝试将我的 Apple Watch 应用程序的一部分置于付费专区之后。为此,iOS 应用程序会自动创建一个具有 true/false 值的字典,无论内容是购买还是否。问题是,无论我如何尝试,我都无法将它传递给手表。

这是我的iOSViewController:

import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
    //The dictionary to be passed to the Watch
    var dictionaryToPass = ["product1": 0, "product2": 0]
    
    
    //This will run, if the connection is successfully completed.
    //BUG: After '.activate()'-ing the session, this function successfully runs in the '.activated' state.
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        print("WCSession - activationDidCompleteWith:", activationState, "and error code:", error as Any)
        switch activationState {
            case .activated:
                print("WCSession - activationDidCompleteWith .activated")
                //session.transferUserInfo(dictionaryToPass)
            case .inactive:
            print("WCSession - activationDidCompleteWith .inactive")
            case .notActivated:
            print("WCSession - activationDidCompleteWith .notActivated")
            default:
                print("WCSession - activationDidCompleteWith: something other ")
                break
            }
    }
    
    
    func sessionDidBecomeInactive(_ session: WCSession) {
        print("WCSession - sessionDidBecomeInactive")
    }
    func sessionDidDeactivate(_ session: WCSession) {
        print("WCSession - sessionDidDeactivate")
    }
    
    
    //Pushing the button on the iOS storyboard will attempt iOS-watchOS connection.
    @IBAction func tuiButton(_ sender: UIButton) {
        let session = WCSession.default
        if session.isReachable {
            session.transferUserInfo(dictionaryToPass)
        } else if WCSession.isSupported() {
            session.delegate = self
            session.activate()
        }
    }
    @IBAction func sendmButton(_ sender: UIButton) {
        let session = WCSession.default
        if session.isReachable {
            session.sendMessage(dictionaryToPass, replyHandler: { reply in
                print(reply)
            }, errorHandler: nil)
        } else if WCSession.isSupported() {
            session.delegate = self
            session.activate()
        }
    }
    
    
}

这就是我在 watchOS 的 Interface Controller:

import WatchConnectivity

class InterfaceController: WKInterfaceController, WCSessionDelegate {
    
    //The text label on the Watch Storyboard. Helps with debugging.
    @IBOutlet weak var helloLabel: WKInterfaceLabel!
    
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        print("watchOS - activationDidCompleteWith:", activationState)
    }
    
    
    //Whatever arrives, it will get printed to the console as well as the 'helloLabel' will be changed to help the debugging progress.
    //BUG: This is the part, that never gets run, even tough the WCSession activated successfully.
    func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
        print("watchOS - didReceiveUserInfo", userInfo)
        helloLabel.setText("didReceiveUserInfo")
    }
    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        print("watchOS - didReceiveMessage", message)
        helloLabel.setText("didReceiveMessage")
    }
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        replyHandler(["does it work?": "yes sir"])
        print("watchOS - didReceiveMessage", message)
        helloLabel.setText("didReceiveMessage")
    }
    
    
    //Setting the Interface Controller as WCSession Delegate
    private var session: WCSession = .default
    override func awake(withContext context: Any?) {
        session.delegate = self
        session.activate()
    }
    
    
    //Activating the session on the watchOS side as well.
    override func willActivate() {
        if WCSession.isSupported() {
                let session = WCSession.default
                session.delegate = self
                session.activate()
            }
    }
    
    
}

更新

在查看您的代码后,我注意到两个主要问题:

  1. 您没有将 InterfaceController 设置为 WCSession 代表。需要从两端激活连接。
class InterfaceController: WKInterfaceController, WCSessionDelegate {

    private var session: WCSession = .default
    
    override func awake(withContext context: Any?) {
        session.delegate = self
        session.activate()
    }

}
  1. 为了能够接收到对方设备的消息,需要实现session(_:didReceiveMessage:replyHandler:)方法。将这些方法添加到您的 InterfaceController:
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
    print("watchOS - didReceiveMessage", message)
}

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    replyHandler(["does it work?": "yes sir"])
    print("watchOS - didReceiveMessage", message)
}

如您所见,我还实现了第二个函数,它可以通过调用传递一些数据来响应 replyHandler。这在调试时很有用。

更新按钮操作和 sendMessage 调用。如果设备已经可以访问,则无需重新激活连接,同时传递回复句柄以确保手表返回数据。

@IBAction func button(_ sender: UIButton) {
    if session.isReachable {
        session.sendMessage(watchInAppPurchases, replyHandler: { reply in
            print(reply)
        }, errorHandler: nil)
    } else if WCSession.isSupported() {
        session.delegate = self
        session.activate()
    }
}

初始答案

不要尝试在调用 activate() 后直接同步数据,因为无法保证连接已经建立。文档明确指出:

This method executes asynchronously and calls the session(_:activationDidCompleteWith:error:) method of your delegate object upon completion.

由于您将 self 设置为委托,请尝试将 transferUserInfo 调用移至 session(_:activationDidCompleteWith:error:) 实现。

func session(
    _ session: WCSession,
    activationDidCompleteWith activationState: WCSessionActivationState,
    error: Error?
) {
    switch activationState {
    case .activated:
        session.transferUserInfo(watchInAppPurchases)
    default:
        // handle other states
        break 
    }
}

此外,在使用 Swift 时,请确保不要对属性、函数等使用 CapitalizedCamelCase 名称。仅对类型使用此表示法。我已将上面代码示例中的原始 WatchInAppPurchases 转换为 watchInAppPurchases

如果您对 transferUserInfo 的调用仍然无效,请尝试调用 sendMessage(_:replyHandler:errorHandler:)

switch activationState {
case .activated:
    session.sendMessage(watchInAppPurchases, replyHandler: nil, errorHandler: nil)
default:
    // handle other states
    break 
}

并监视 session(_:didReceiveMessage:replyHandler:) 中的任何传入消息的扩展。

原来是 watchOS 模拟器出了问题。苹果的好可惜。

Further reading on Apple's forum: https://developer.apple.com/forums/thread/127460

如果其他人有同样的想法,我推荐 运行 物理设备上的代码,它在那里工作得很好。如果 Google 结果中的任何人正在寻找最终的工作代码,可以找到 here