WCSession becomes unresponsive after a few seconds of not sending messages

206 views Asked by At

I'm trying to use WCSession in Swift 3 to send messages from a WatchKit Extension to the iPhone app and reply with some data.

The first time I'm sending a message I get a reply in about 2s. If I send a message directly or max. after 3-5 seconds after the last message I still get a reply within 2s. But if I wait for longer than that (for example 10s) after the last message I will either get no reply at all or a reply after more than 30s.

Am I doing something wrong in my code or is that a bug?

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")
}

...

Watch 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)")
}
0

There are 0 answers