尝试将我的Watch OS1应用程序升级到Watch OS 2.为Watch OS 2创建新目标。并使用sendMessage:replyHandler:errorHandler
发送/获取来自IOS应用程序的回复。只有在IOS应用程序运行时它才能正常工作。如果Watch应用程序在iOS应用程序处于非活动状态(Killed State)时尝试通信,则会出现连接错误7001.如何从Watch App(Watch OS 2)传递非活动IOS应用程序?
来自watch app的这个sendMessage:replyHandler:errorHandler
方法是否会在后台唤醒相应的iOS应用并使其可以访问?
感谢。
EDIT1: -
iOS APP的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.
}
];
}
答案 0 :(得分:0)
由于activate方法是异步的,所以在委托方法中使用它如下:
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")
}
}