如何通过Watch App(Watch OS 2)沟通非活动IOS应用程序
问题描述:
试图将我的Watch OS1应用程序升级到Watch OS 2.创建Watch OS 2的新目标。并使用sendMessage:replyHandler:errorHandler
发送/从IOS应用程序获取回复。它工作正常,如果只有IOS应用程序正在运行。如果Watch应用程序在iOS应用程序处于非活动状态(Killed状态)时尝试通信,则连接错误为7001.如何从Watch App(Watch OS 2)通信非活动的IOS应用程序?如何通过Watch App(Watch OS 2)沟通非活动IOS应用程序
这个来自手表应用的sendMessage:replyHandler:errorHandler
方法会在后台唤醒相应的iOS应用并使其可达?
谢谢。
EDIT1 -
iOS应用程序的App代表:
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
return YES;
}
- (void)session:(nonnull WCSession *)session didReceiveMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * __nonnull))replyHandler {
UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier identifier = UIBackgroundTaskInvalid;
dispatch_block_t endBlock =^{
if (identifier != UIBackgroundTaskInvalid) {
[application endBackgroundTask:identifier];
}
identifier = UIBackgroundTaskInvalid;
};
identifier = [application beginBackgroundTaskWithExpirationHandler:endBlock];
if (replyHandler!=nil) {
replyHandler(resultContainer); // my data dictionary from Iphone app to watch os as reply.
}
if (identifier!=UIBackgroundTaskInvalid) {
[application endBackgroundTask:identifier];
identifier = UIBackgroundTaskInvalid;
}
}
关注应用:
- (void)applicationDidFinishLaunching {
// Perform any final initialization of your application.
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
NSDictionary *context = @{@"APP_LOADING":@"LOADING"};
[WKInterfaceController reloadRootControllersWithNames:@[WATCH_INTERFACE_LOADING] contexts:@[context]];
NSDictionary *request = //My Request data;
[[WCSession defaultSession] sendMessage:request
replyHandler:^(NSDictionary *reply) {
//handle reply from iPhone app here
NSDictionary *resultDict = [reply objectForKey:WATCH_REQUEST_RESULT];
// Use reply from Phone app
}
errorHandler:^(NSError *error) {
//catch any errors here
// Getting error here 7001 Error.
}
];
}
答
由于激活方法是异步的使用是在委托方法类似如下:
public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?){
print("activationDidCompleteWith")
if activationState == WCSessionActivationState.activated {
NSLog("Activated")
if(WCSession.default().isReachable){
do {
try session.updateApplicationContext(
[WatchRequestKey : "updateData"]
)
}
catch let error as NSError {
print("\(error.localizedDescription)")
}
}
}
if activationState == WCSessionActivationState.inactive {
NSLog("Inactive")
}
if activationState == WCSessionActivationState.notActivated {
NSLog("NotActivated")
}
}