观看连接无法正常工作

时间:2016-08-01 17:05:04

标签: objective-c watchkit watchconnectivity wcsession

我正在尝试创建一个应用程序,我可以将信息从Apple Watch发送到我的ios Parent App。我已经为它编写了代码但是当我运行WatchConnectivity App时,信息不会在apple watch和父ios应用程序之间传输。这可能是我的代码的问题,也可能是因为某些原因,手表不是从应用程序开始的。我必须去模拟器并点击应用程序才能启动它。这就是为什么我的代码无效?

InterfaceController.m

#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>

@interface InterfaceController() <WCSessionDelegate>

@property (strong, nonatomic) WCSession *session;

@end

@implementation InterfaceController

-(instancetype)init {
    self = [super init];

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


- (IBAction)catPressed {
     [self sendText:@"cat"];
}
- (IBAction)dogPressed {
     [self sendText:@"dog"];
}
- (IBAction)pandaPressed {
    [self sendText:@"panda"];
}
- (IBAction)bunnyPressed {
    [self sendText:@"bunny"];
 }

-(void)sendText:(NSString *)text {
     NSDictionary *applicationDict = @{@"emoji":text};
     [self.session updateApplicationContext:applicationDict error:nil];

}

ViewController.m

#import "ViewController.h"
#import <WatchConnectivity/WatchConnectivity.h>

@interface ViewController () <WCSessionDelegate>
@property (weak, nonatomic) IBOutlet UILabel *textLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
     [super viewDidLoad];

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

         NSLog(@"HIIII");
     }
 }

 - (void)session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,id> *)applicationContext {

    NSString *text = [applicationContext objectForKey:@"text"];

    dispatch_async(dispatch_get_main_queue(), ^{
    [self.textLabel setText:[NSString stringWithFormat:@"Text: %@", text]];
    });
}

1 个答案:

答案 0 :(得分:0)

事实证明,我需要先在iPhone上打开父应用程序才能开始在iPhone和Watch之间共享信息。感谢MSU_Bulldog提出这个想法。