0

我正在尝试在 Swift 3 中使用 WCSession 将消息从 WatchKit 扩展发送到 iPhone 应用程序并回复一些数据。

我第一次发送消息时,我会在大约 2 秒内收到回复。如果我直接发送消息或最多发送消息。在最后一条消息后 3-5 秒后,我仍然在 2 秒内收到回复。但是,如果我在最后一条消息之后等待的时间比这更长(例如 10 秒),我将要么根本没有回复,要么会在 30 多秒后得到回复。

我在我的代码中做错了什么还是一个错误?

应用委托:

import UIKit
import WatchConnectivity

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {

var window: UIWindow?
var session : WCSession?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    if WCSession.isSupported() {
        session = WCSession.default()
        session?.delegate = self
        session?.activate()
    }

    return true
}

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    if (message["message"] != nil) {
        replyHandler(["response": "ok"])
    }
}

func session(_ session:WCSession, activationDidCompleteWith: WCSessionActivationState, error: Error?) {
    print("Session activation did complete")
}

func sessionDidBecomeInactive(_ session: WCSession) {
    print("Session did become inactive.")
}

func sessionDidDeactivate(_ session: WCSession) {
    print("Session did deactivate")
}

...

观察接口控制器:

import WatchKit
import Foundation
import WatchConnectivity

class InterfaceController: WKInterfaceController, WCSessionDelegate {

var session : WCSession?

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    session = WCSession.default()
    session?.delegate = self
    session?.activate()
}

@IBAction func sendMessageButtonPressed() {
    let reply: ([String:Any]) -> Void = {(dataMessage : [String:Any]) -> Void in
        print("Data: \(dataMessage)");
    }

    let error : (Error) -> Void = {(error : Error) -> Void in
        print("Error: \(error)")
    }

    if (session?.isReachable)! {
        print("Message Send")
        session?.sendMessage(["message": "test"], replyHandler: reply, errorHandler: error)
    }
    else {
        print("Message not send")
    }
}

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

0 回答 0