func session(..) 在 WatchKit 中没有被调用

func session(..) doesn't get called in WatchKit

我尝试了 3 天来完成这项工作,但没有成功:/

我想向我的手表发送一些消息。但是函数会话没有被调用。

在我的 parent 中,我使用此代码打开会话:

- (void)viewDidLoad {

     [super viewDidLoad];

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

}

然后我想在按下按钮时向我的应用程序发送字典:

 -(void)clickBackButton{

     NSArray *obj = @[@"Mercedes-Benz SLK250", @"Mercedes-Benz E350"];
     NSArray *key = @[[NSNumber numberWithInt:13], [NSNumber numberWithInt:22]];
     NSDictionary *applicationDict = [NSDictionary dictionaryWithObject:obj forKey:key];
     [[WCSession defaultSession] transferUserInfo:applicationDict];

 }

在我的手表中,我将此代码用于会话:

 override func willActivate() {
    super.willActivate()

    if (WCSession.isSupported()) {
        session = WCSession.defaultSession()
        session.delegate = self
        session.activateSession()
    }
}

并且此方法永远不会被调用:

func session(session: WCSession, didFinishUserInfoTransfer userInfoTransfer: WCSessionUserInfoTransfer, error: NSError?) {
    print("session called")
}

您要查找的委托方法是session:didReceiveUserInfo:。如果您阅读委托方法上方的评论,您会看到您在接收方(在您的情况下是手表)实现的方法是在发送方调用以确认传输完成的方法!

    /** Called on the sending side after the user info transfer has successfully completed or failed with an error. Will be called on next launch if the sender was not running when the user info finished. */
- (void)session:(WCSession * __nonnull)session didFinishUserInfoTransfer:(WCSessionUserInfoTransfer *)userInfoTransfer error:(nullable NSError *)error;

/** Called on the delegate of the receiver. Will be called on startup if the user info finished transferring when the receiver was not running. */
- (void)session:(WCSession *)session didReceiveUserInfo:(NSDictionary<NSString *, id> *)userInfo;