Watch OS app not able to connect with iOS app

十年热恋 提交于 2020-07-18 17:44:07

问题


I am trying to connect my Watch OS app with iOS app and fetch some data but I am getting following error when I try to connect with iOS app:

[WC] __28-[WCSession activateSession]_block_invoke_2 sessionReadyForInitialStateWithCompletionHandler failed due to NSXPCConnectionInterrupted

__44-[WCSession updateApplicationContext:error:]_block_invoke failed due to WCErrorCodeSessionNotActivated WatchConnectivity session has not been activated.

iOS app Code:

- (void) startSession{
if ([WCSession isSupported]) {
    self.session = [WCSession defaultSession];
    self.session.delegate = self;
    [self.session activateSession];
}

}

Watch OS Code:

func startSession() {
    if(session.activationState != .activated){
        session.delegate = self
        session.activate()
    }
}
public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?){
    print("activationDidCompleteWith")
    if activationState == WCSessionActivationState.activated {
        NSLog("Activated")
        if(WCSession.default().isReachable){

            do {
                try session.updateApplicationContext(
                    [WatchRequestKey : "updateData"]
                )
            }
            catch let error as NSError {
                print("\(error.localizedDescription)")
            }
        }
    }
    
    if activationState == WCSessionActivationState.inactive {
        NSLog("Inactive")
    }
    
    if activationState == WCSessionActivationState.notActivated {
        NSLog("NotActivated")
    }
}

iOS app is in objective C and watch app is in swift

I execute my iOS app code first and it's delegate methods run but when I run watch os app it fails to execute any delegate method, and produce above error.


回答1:


The activate() method runs asynchronously from Watch OS v2.2 onwards. So, in your code, calling updateApplicationContext just after invoking activate() does not provide any guarantee that the session will be actually activated when trying to update the application context.

The correct flow would be to move your message to session(_:activationDidCompleteWith:error:), as for example:

func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    if activationState == .activated {
       // Update application context here
    }
}


来源:https://stackoverflow.com/questions/41896818/watch-os-app-not-able-to-connect-with-ios-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!