我正在尝试在Swift 3中使用WCSession将来自WatchKit Extension的消息发送到iPhone应用程序并回复一些数据。
我第一次发送消息时,我得到了大约2s的回复。如果我直接发送消息或最多在最后一条消息发生3-5秒后,我仍然在2秒内收到回复。但是,如果我在最后一条消息之后等待的时间超过了(例如10秒),我将无法得到任何回复或超过30秒后回复。
我在代码中做错了还是错误?
的AppDelegate:
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")
}
...
观看InterfaceController:
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)")
}