Apple Watch 未将数据传递给 iPhone - Swift

Apple Watch Not Passing Data to iPhone - Swift

我正在尝试将一个字符串从我的 Apple Watch 传递到 iPhone,但它似乎没有连接。这是我的代码:

ViewController.swift :

import UIKit
import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {

    @IBOutlet weak var lablel: UILabel!
    var string = "Hello World"
    let session = WCSession.default()


    override func viewDidLoad() {
        super.viewDidLoad()

        session.delegate = self
        session.activate()

    }


    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        let msg = message["StringValueSentFromiWatch"] as! String
        lablel.text = "Message : \(msg)"

        print("iphone recieved message")
    }

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

    }

    func sessionDidBecomeInactive(_ session: WCSession) {

    }

    func sessionDidDeactivate(_ session: WCSession) {

    }
}

InterfaceController.swift :

import WatchKit
import Foundation
import WatchConnectivity


class InterfaceController: WKInterfaceController, WCSessionDelegate {

     let session = WCSession.default()

    override func willActivate() {
        super.willActivate()

        session.delegate = self
        session.activate()
    }

    @IBAction func SendPressed() {

        //Send Data to iOS
        let msg = ["StringValueSentFromiWatch" : "Hello World"]
        session.sendMessage(msg, replyHandler: { (replay) -> Void in
            print("apple watch sent")
        }) { (error) -> Void in
         print("apple watch sent error")
        }

    }

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

}

我正在尝试将 "Hello World" 发送到 iPhone 但我在控制台中得到了以下打印输出:

errorHandler: YES with WCErrorCodePayloadUnsupportedTypes

和'apple watch sent error'.

我知道它没有发送,但我不知道为什么。有谁知道为什么这不起作用?

注意:我 运行 这是模拟器,但我很确定这不是问题所在。

我认为您在 sendMessage() 中搞砸了,我无法计算出 replyHandler 语法,并且您错过了 errorHandler: 参数。

无论如何,我已经尝试了您的代码,稍作改动就可以了。

1).在 InterfaceController 中,sendPressed():

    var count = 0    
@IBAction func SendPressed() {
    //Send Data to iOS
    let msg = ["Count" : "\(count)"]

    if session.isReachable {
        session.sendMessage(msg, replyHandler: nil, errorHandler: { (error) -> Void in
            print("Error handler: \(error)")
        })
        count += 1
    }
}

我添加了一个计数,因为每次通话的消息必须不同(以节省电量),因此您现在可以连续多次按下按钮。并检查以验证主机应用程序是否可访问。

2.) 在ViewController中,记得在主线程上更新GUI:

    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
    DispatchQueue.main.async {
        self.lablel.text = "Message : \(message)"
    }
}

否则标签不会在您收到数据时更新。

如果对你有帮助,请告诉我!