2016-08-01 51 views
0

我想創建一個應用程序,我可以從蘋果手錶發送信息到我的ios父應用程序。我爲它編寫了代碼,但是當我運行WatchConnectivity應用程序時,信息不會在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]]; 
    }); 
} 
+0

我也經歷過這種情況,我需要首先在iPhone上打開父應用程序以開始在iPhone和Watch之間共享信息 –

回答

0

事實證明,我需要打開iPhone上的父應用程序率先啓動iPhone之間共享信息和觀察。感謝MSU_Bulldog提出這個想法。