Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch OS app not able to connect with iOS app

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.

like image 550
pankaj Avatar asked Jan 27 '17 14:01

pankaj


1 Answers

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
    }
}
like image 51
spassas Avatar answered Sep 29 '22 01:09

spassas