ios - 使用 watchOS 2 从 Apple Watch 向 iPhone 应用程序发送消息

标签 ios objective-c watchkit

我尝试使用 WCSession 方法从 iwatchExtension(在 ButtonClick 上)向 iPhone 应用发送消息

[[WCSession defaultSession] sendMessage:applicationData
                                   replyHandler:^(NSDictionary *reply)

但是委托(delegate)方法 - (void)session:(WCSession *)session didReceiveMessage: 未被调用。

当我尝试将数据从 iPhone 传递到 iWatch 时,它工作正常。在“Extension Delegate”类中正确调用所有委托(delegate)方法。

最佳答案

如果你检查 WCSession 的定义委托(delegate)方法,您会发现它们的接收性质有细微差别。检查粗体引号。

/** Called on the delegate of the receiver. Will be called on startup if the incoming message caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary *)message;

/** Called on the delegate of the receiver when the sender sends a message that expects a reply. Will be called on startup if the incoming message caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary *)message replyHandler:(void(^)(NSDictionary *replyMessage))replyHandler;

因为您为 replyHandler: 提供了一个非空参数,您应该在其他代表中收到消息,即 -(void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message .

您正在使用 [WCSession defaultSession] sendMessage: ...] 进行通信,缺少委托(delegate)分配而且您还没有激活 session 。

在您的扩展类中,为 WCSession 创建一个 ivar并编写这段代码

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];
    // Configure interface objects here.    
    if([WCSession isSupported])
    {
        session = [WCSession defaultSession];
        session.delegate = self;
        [session activateSession];
    }    
}

然后发送类似[session sendMessage:applicationData replyHandler:^(NSDictionary *reply)的消息.

在你的AppDelegate.m文件只是创建 WCSession 的实例并激活它并使用正确的 delegate方法来捕获消息。

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

我相信这应该可以解决您的问题。

关于ios - 使用 watchOS 2 从 Apple Watch 向 iPhone 应用程序发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34268965/

相关文章:

objective-c - 核心数据和 NSPersistentDocument : Sum of column numbers crash

iphone - 我们可以在第三方应用程序中使用默认系统声音吗?

ios - 使用 Replaykit 进行直播

actionscript-3 - 如何在iOS包中打开一个NetStream using video?

iphone - Facebook图api数据与IOS应用程序数据不一致

ios - 如何在 objective-c 中使用 nsurl 在 url 查询参数中传递数组?

ios - GLKView 后面的 UIImage

swift - 如何将后台应用程序刷新添加到 swift WatchOs 应用程序

ios - WatchKit:WKInterfaceMap 中的 setVisibleMapRect 与 setRegion

ios - 自定义字体在 WatchKit InterfaceFile 中显示自定义(未安装)