簡體   English   中英

使用watchOS2將消息從AppleWatch發送到iPhone應用程序

[英]send message from AppleWatch to iPhone app using watchOS2

我試圖使用WCSession方法從iwatchExtension(on ButtonClick)將消息發送到iPhone應用程序

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

但是委托方法- (void)session:(WCSession *)session didReceiveMessage:沒有被調用。

當我在將數據從iPhone傳遞到iWatch時嘗試相同的操作時,它可以正常工作。 所有委托方法都可以在“擴展委托”類中正確調用。

如果檢查WCSession委托方法的定義,則會發現它們的接收性質略有不同。 檢查粗體報價。

/ **調用接收者的代表。 如果傳入消息導致接收器啟動,則在啟動時將被調用。 * /
-(void)session:(WCSession *)session didReceiveMessage:(NSDictionary *)message;

/ ** 當發送方發送需要回復的消息時,調用接收的委托。 如果傳入消息導致接收器啟動,則在啟動時將被調用。 * /
-(void)session:(WCSession *)session didReceiveMessage:(NSDictionary *)消息ReplyHandler:(void(^)(NSDictionary * replyMessage))replyHandler;

當您為replyHandler:提供一個非null參數時,您應該在其他委托中接收消息,即-(void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message

您正在使用[WCSession defaultSession] sendMessage:...]進行通信,該通信缺少委托分配,並且您尚未激活會話。

在您的Extention類中,為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];
}

我相信這應該可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM