WCSession sendMessage:replyHandler error code 7014 (WCErrorCodeDeliveryFailed)

徘徊边缘 提交于 2019-12-04 09:00:28

问题


I have a Watch OS 2 application that communicates with the iOS app via WCSession method sendMessage:replyHandler:errorHandler:

The iOS application reply correctly but time to time I get the error with code 7014 of domain WCErrorDomain: "Payload could not be delivered"

It happens more often when the iOS application is not foreground.

I do not find any solution of this problem, I hope one of you know a solution to this problem


回答1:


For anyone having issues on iOS10 beta 6 and GM, and you are using Swift3, the solution is to change the delegate function header in the iOS app to the following:

    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {

Note the @escaping and the Any instead of the AnyObject type.




回答2:


In my case, I had to implement both delegates:

  1. The one without any replyHandler

    func session(_ session: WCSession,
                     didReceiveMessage message: [String : Any])
    
  2. The one with replyHandler

    func session(_ session: WCSession,
                 didReceiveMessage message: [String : Any],
                 replyHandler: @escaping ([String : Any]) -> Void)
    

If you send a message without a replyHandler then the first delegate runs.
If you send a message with a replyHandler then the second delegate runs.


In some cases I was sending only a message, and in other cases I was sending a message and expecting a reply from the counterpart.
BUT... I had implemented only the second delegate -_-

Anyways, eventually to reduce duplicate code I implemented a common method and ended up with:

func session(_ session: WCSession,
             didReceiveMessage message: [String : Any]) {
    handleSession(session, 
                  didReceiveMessage: message)
}

func session(_ session: WCSession,
             didReceiveMessage message: [String : Any],
             replyHandler: @escaping ([String : Any]) -> Void) {
    handleSession(session, 
                  didReceiveMessage: message, 
                  replyHandler: replyHandler)
}

//Helper Method
func handleSession(_ session: WCSession,
                   didReceiveMessage message: [String : Any],
                   replyHandler: (([String : Any]) -> Void)? = nil) {
    //Common logic
}

Watch OS 4




回答3:


Try this one, this fixed my issue. Inside the InterfaceController add the following methods for passing the data to phone.

-(void)sendDataToPhone:(NSDictionary* _Nonnull)dictData
{
    if(WCSession.isSupported){

        WCSession* session = WCSession.defaultSession;
        session.delegate = self;
        [session activateSession];

        if(session.reachable)
        {
            [session sendMessage:dictData replyHandler: ^(NSDictionary<NSString *,id> * __nonnull replyMessage) {

                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@".....replyHandler called --- %@",replyMessage);
                    // Play a sound in watch
                    [[WKInterfaceDevice currentDevice] playHaptic:WKHapticTypeSuccess];
                });
            }
                    errorHandler:^(NSError * __nonnull error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"Error = %@",error.localizedDescription);
                        });
                    }
             ];
        }
        else
            NSLog(@"Session Not reachable");
    }
    else
        NSLog(@"Session Not Supported");
}



#pragma mark - Standard WatchKit delegate

-(void)sessionWatchStateDidChange:(nonnull WCSession *)session
{
    if(WCSession.isSupported){
        WCSession* session = WCSession.defaultSession;
        session.delegate = self;
        [session activateSession];

    }
}

In the phone side, add the following codes for receiving the data from watch.

Add the following in didFinishLaunchingWithOptions.

// Allocating WCSession inorder to communicate back to watch.
    if(WCSession.isSupported){
        WCSession* session = WCSession.defaultSession;
        session.delegate = self;
        [session activateSession];
    }

Now add the WCSessionDelegate.

#pragma mark - WCSession Delegate

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler
{
    if(message){
        NSData *receivedData = [message objectForKey:@"AudioData"];
        NSDictionary* response = @{@"response" : [NSString stringWithFormat:@"Data length: %lu",(unsigned long)receivedData.length]} ;
        replyHandler(response);
    }
}


#pragma mark - Standard WatchKit Delegate

-(void)sessionWatchStateDidChange:(nonnull WCSession *)session
{
    if(WCSession.isSupported){
        WCSession* session = WCSession.defaultSession;
        session.delegate = self;
        [session activateSession];

        if(session.reachable){
            NSLog(@"session.reachable");
        }

        if(session.paired){
            if(session.isWatchAppInstalled){

                if(session.watchDirectoryURL != nil){

                }
            }
        }
    }
}

Hope this helps you :)




回答4:


Sorry I'dont have enough reputation to comment answers. My issue got resolved with Peter Robert's answer: With Swift 3 WCErrorCodeDeliveryFailed appeared and the solution was simply changing AnyObject to Any on the replyHandlers.

    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
//code
 replyHandler (answer as [String : Any])
}



回答5:


I was experiencing the same and moving WCSession initialization (setting delegate and activating it) later in the app lifecycle fixed the issue.

I had WCSession activation in app delegates didFinishLaunching and having it there broke the communication. Moving WCSession intialization later in the app made comms work again.




回答6:


You may need to (check and) implement that your WCSession delegate implemented the following method. I got this error due to missing the implementation.

- (void)session:(WCSession * _Nonnull)session
didReceiveMessage:(NSDictionary<NSString *, id> * _Nonnull)replyMessage
   replyHandler:(void (^ _Nonnull)(NSDictionary<NSString *, id> * _Nonnull replyMessage))replyHandler
{
    NSLog(@"Received. %@", replyMessage);
    [self processResponse:replyMessage];
}



回答7:


Check the delegate connected correct ?

 WCSession* session = WCSession.defaultSession;
 session.delegate = self;
 [session activateSession];

Note : Verify session.delegate = self; set to self.




回答8:


Working on an app and have the exact same behavior. I feel fairly sure that I have looked everywhere in my code and found nothing wrong. My best guess is that this must be a bug with WatchConnectivity.

My current error handler workaround simply tries to reload data on this particular error. Not very beautiful, but it works ok.

You might want to try something similar?

func messageErrorHandler(error: NSError) {
  isLoading = false
  print("Error Code: \(error.code)\n\(error.localizedDescription)")

  // TODO: WTF?. Check future releases for fix on error 7014, and remove this...
  if error.code == 7014 {
    // Retry after 1.5 seconds...
    retryTimer = NSTimer.scheduledTimerWithTimeInterval(
      NSTimeInterval(1.5), target: self, selector: "reloadData", userInfo: nil, repeats: false)
    return
  }

  displayError("\(error.localizedDescription) (\(error.code))",
    message: "\(error.localizedDescription)")
}

UPDATE:

For anyone working with WatchConnectivity; I need to have a similar "hack" for testing the session.reachable variable.

I have noticed that my app manages to send a message before the session becomes reachable. So I simply try to reload data (re-send the message) a couple of times before actually telling the user their phone is out of reach.

UPDATE 2: The above example is using .sessionWatchStateDidChange(), so the issue is not that .sendMessage() is triggered too early because of not waiting for connection ack. This must be a bug as it is not happening every time, it just freaks out like 1 per 100 messages.




回答9:


I have found that putting the reply code as the first thing to run fixes this issue (possible being caused by timing out?).

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: ([String : Any]) -> Void) {
    print("Message - received")

    //Send reply
    let data = ["receivedData" : true]
    replyHandler(data as [String : AnyObject])

}



回答10:


In Swift 3 I solved implementing didReceiveMessage with this signature:

func session(_ session: WCSession, didReceiveMessage message: [String : Any],
             replyHandler: @escaping ([String : Any]) -> Void)



回答11:


Be sure that your Session is always active. I for example had an other View which was part of the testing and then returned on the initially View and was wondering why the Session wasn't active anymore.

- (void)willActivate {
// This method is called when watch view controller is about to be visible to user
[super willActivate];

//Setup WCSession
if ([WCSession isSupported]) {
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}}

Above did it for me. Had it first placed in the awakeWithContext, stupid me....




回答12:


This scenario will cover several use case. Please take look at these steps , it help me a lot.

1 - Understand that each device must have their own WCSession instance configured and with the appropriate delegates configured.

2 - implement WCSessionDelegate only at one single place on each device, ej. on iOS app on the AppDelegate, on watchOS on ExtensionDelegate. This is very important because with the appropriate WCSession configured on watchOS but on iPhone implementing on two different place, ej. on app delegate and then on the first viewcontorllweer of the app, (on my case ) lead to unstable behaviour and thats the main reason why sometimes the iOS app stop responding when message received from watch.

3 - reactivating the session is advisable only do it on the Host App. This is an example of my iOS App with only one WCSessionDelegate. (AppDelegate )


#pragma mark - WCSessionDelegate

- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(NSError *)error{

    if( activationState == WCSessionActivationStateActivated) {
        NSLog(@"iPhone WKit session Activated");
    }else if (activationState == WCSessionActivationStateInactive) {
        NSLog(@"iPhone WKit Inactive");
    }else if (activationState == WCSessionActivationStateNotActivated) {
        NSLog(@"iPhone WKit NotActivated");
    }
}



- (void)sessionDidBecomeInactive:(WCSession *)session{
    /*
     The session calls this method when it detects that the user has switched to a different Apple Watch. While in the inactive state, the session delivers any pending data to your delegate object and prevents you from initiating any new data transfers. After the last transfer finishes, the session moves to the deactivated state
     */
    NSLog(@"sessionDidBecomeInactive");

    if (session.hasContentPending) {
        NSLog(@"inactive w/ pending content");
    }
}




- (void)sessionDidDeactivate:(WCSession *)session{
    // Begin the activation process for the new Apple Watch.
    [[WCSession defaultSession] activateSession];

    //perform any final cleanup tasks related to closing out the previous session.
}





- (void)sessionReachabilityDidChange:(WCSession *)session{
    NSLog(@"sessionReachabilityDidChange");
}

last thing, write the appropriate method signature, if you need a reply sending data from watch , take the method signature who have reply:... According to apple the following methods


sendMessage:replyHandler:errorHandler:, sendMessageData:replyHandler:errorHandler:, and transferCurrentComplicationUserInfo: 

has a higher priority and is transmitted right away. All messages received by your app are delivered to the session delegate serially on a background thread.

So do not waste time dispatching the reply object on mainQueue on the iOS appDelegate, wait till you have the response on your watchOS back and change it to main thread to update your UI accordingly.




回答13:


In my case I put WCSessionDelegate(iOS side) in a separate class and initialize it as local variable. Changing it to global instance variable solved the issue.

So my iOS Code was:

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

Changed to below to get it working:

var handler: SessionHandler!

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


来源:https://stackoverflow.com/questions/33200630/wcsession-sendmessagereplyhandler-error-code-7014-wcerrorcodedeliveryfailed

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