簡體   English   中英

iOS - WatchKit如何將消息/數據從iPhone應用程序發送到WatchKit應用程序?

[英]iOS - WatchKit how to send message/data from iPhone app to WatchKit app?

我正在創建一個WatchKit應用程序,並想知道如何從iPhone發送消息/數據到手表?

我知道如何使用' openParentApplication:reply: '和' application:handleWatchKitExtensionRequest:reply: '來反過來 (手表 - >手機),但找不到任何關於如何通過手機進行通信的文檔。

簡單的設置將是iPhone應用程序有一個按鈕,按下時應該更新Watch應用程序上的標簽。

誰能指出我正確的方向?

首先,您必須為目標啟用應用組:

在此輸入圖像描述

然后您可以通過NSUserDefaults開始編寫和讀取對象:

// write 
let sharedDefaults = NSUserDefaults(suiteName: appGroupName)
sharedDefaults?.setInteger(1, forKey: "myIntKey")


// read
let sharedDefaults = NSUserDefaults(suiteName: appGroupName)
let myIntValue = sharedDefaults?.integerForKey("myIntKey")

請參閱“ Apple Watch編程指南:為Apple Watch開發”中的“ 與包含iOS應用程序共享數據 ”一章

這對我有用。 嘗試使用手表

- (void)registerToNotification
{
    [ self unregisterToNotification ];
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), didReceivedDarwinNotification, CFSTR("NOTIFICATION_TO_WATCH"), NULL, CFNotificationSuspensionBehaviorDrop);
}

- (void)unregisterToNotification
{
    CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), CFSTR( "NOTIFICATION_TO_WATCH" ), NULL );
}

void didReceivedDarwinNotification()
{
    // your code
}

在主應用程序中

- (void)sendNotificationToWatch:(NSDictionary*)info
{
    CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFSTR("NOTIFICATION_TO_WATCH"), (__bridge const void *)(self), nil, TRUE);
}

您應該嘗試使用App Groups,它們用於在iOS應用和App Extensions之間共享數據。

在Apple Watch應用程序界面控制器類中:

    let sharedDefaults = NSUserDefaults(suiteName: "group.com.<domain>.<appname>.AppShare")
    sharedDefaults?.setObject("Came from Apple Watch App", forKey: "AppleWatchData")
    sharedDefaults?.synchronize()

在您的父應用中:

    let sharedDefaults = NSUserDefaults(suiteName: "group.com.<domain>.<appname>.AppShare")

    if let appWatchData = sharedDefaults?.objectForKey("AppleWatchData") as? NSString {
        println(appWatchData)
    }

“AppShare”是您為父應用目標在功能中創建應用組時指定的名稱。

watchOS 2.0有一個新的框架,稱為Watch Connectivity Framework ,可讓您在兩個設備之間發送消息。

該框架提供了雙向通信通道,用於在兩個進程之間發送文件和數據字典

請參閱此處的示例,包括使用調試模式發送實際字典的示例。

維基例子也可用

祝好運。

或者,

您可以使用此解決方案甚至在2個不同的應用程序之間共享文件,當然還可以在監視應用程序(Extension)和父iOS應用程序之間

第一步由@zisoft描述,啟用應用程序組。

然后在運行時獲取組容器的URL,

- (NSString *)containerPath
{
    return [[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"YOUR_APP_GROUP"] relativePath];
}

現在您可以在給定路徑上編寫任何文件/文件夾,下面是我的示例代碼段,

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.array];

NSString *path = [[[self containerPath] stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"history"];

if ([data writeToFile:path atomically:YES])
{
    NSLog(@"Success");
}
else
{
    NSLog(@"Failed");
}

暫無
暫無

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

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