使用MMWormhole将消息传递给Apple Watch

时间:2015-04-13 15:23:23

标签: ios objective-c iphone watchkit apple-watch

我正在开发Apple Watch App,我需要在父应用程序发生某些更改时通知手表。我正在使用GitHub上的MMWormhole库,但是我在将消息从手机传递到手表时遇到了麻烦。这是我的代码,您对此为何发生了什么想法?

我的主视图控制器代码如下所示

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    self.wormhole = [[MMWormhole alloc] initWithApplicationGroupIdentifier:@"com.mycompany.myapp"
                                                         optionalDirectory:@"wormhole"];

    NSString *myString = [[NSString alloc] initWithFormat:@"Test String"];


    [self.wormhole passMessageObject:@{@"string" : myString}
                      identifier:@"messageIdentifier"];

我的InterfaceController中的WatchkitExtension如下所示:

InterfaceController.m

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    // Initialize the wormhole
    self.wormhole = [[MMWormhole alloc] initWithApplicationGroupIdentifier:@"com.mycompany.myapp"
                                                         optionalDirectory:@"wormhole"];

    // Obtain an initial value for the selection message from the wormhole
    id messageObject = [self.wormhole messageWithIdentifier:@"messageIdentifier"];

    NSString *string = [messageObject valueForKey:@"string"];

    if (string != nil) {
        NSLog(string);
        [myLabel setText:string];
    }

    // Listen for changes to the selection message. The selection message contains a string value
    // identified by the selectionString key. Note that the type of the key is included in the
    // name of the key.
    [self.wormhole listenForMessageWithIdentifier:@"messageIdentifier" listener:^(id messageObject) {

        NSString *string = [messageObject valueForKey:@"string"];

        if (string != nil) {
            [self.myLabel setText:string];
        }
    }];                                    
}

谢谢!

1 个答案:

答案 0 :(得分:1)

"com.mycompany.myapp"是您在应用中使用的真正价值吗?因为组标识符必须以group.开头。

如果使用错误的组标识符,则一切都会失败,因为MMWormhole内的containerURLForSecurityApplicationGroupIdentifier调用返回nil。不幸的是,MMWormhole的开发人员没有做任何检查或断言以确保共享组标识符是正确的。

所以我建议停止专注于MMWormhole一分钟。而是在代码的早期添加此代码(例如applicationDidFinishLaunching)以验证您的容器标识符是否正确:

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSURL *appGroupContainer = [fileManager containerURLForSecurityApplicationGroupIdentifier:@"group.com.mycompany.myapp"];
if (!appGroupContainer) {
    NSLog(@"group identifier incorrect, or app groups not setup correctly");
}

这将告诉您应用组设置是否不正确。

我不确定您在设置应用程序组方面有多远,但您必须使用项目的应用程序组功能部分中使用的组标识符。

enter image description here

相关问题