0

Apple Watch から 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]];
    });
}
4

1 に答える 1

0

iPhone と Watch の間で情報を共有するには、まず iPhone で親アプリを開く必要があることがわかりました。このアイデアを提案してくれた MSU_Bulldog に感謝します。

于 2016-08-05T17:19:19.183 に答える