我有一个非常丰富的网络层的应用程序,我的苹果手表应用程序依赖于所有的模型。不幸的是,该应用程序不够模块化,无法在手表应用程序中使用这一层。
我使用openParentApplication解决了这个问题:唤醒iPhone应用程序,执行请求并返回结果。
在watchOS 2中,这个方法消失了,我应该使用WatchConnectivity。最好的使用方法是发送userInfo字典。
但是我如何唤醒iPhone应用程序来处理我的请求呢?要获得关于新userInfos的通知,我必须使用WCSessionDelegate,为此需要一个WCSession对象。但我什么时候才能创造呢?以及如何唤醒这个应用程序?
发布于 2015-08-03 15:03:22
我问了一位苹果工程师,并得到了以下提示: iOS-App应该在后台任务中启动。因此,以下几点对我来说非常有效:
UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier identifier = UIBackgroundTaskInvalid;
dispatch_block_t endBlock = ^ {
if (identifier != UIBackgroundTaskInvalid) {
[application endBackgroundTask:identifier];
}
identifier = UIBackgroundTaskInvalid;
};
identifier = [application beginBackgroundTaskWithExpirationHandler:endBlock];将其添加到session:didReceiveMessage:或session:didReceiveMessageData:方法中,以便在超时3分钟的情况下启动后台任务。
发布于 2015-10-21 19:32:36
以下是本杰明·赫尔佐格的建议的迅速版本。值得注意的是,虽然我确实选择将由Watch启动的工作推送到后台任务,但只要我的应用程序处于后台,系统就会唤醒它。在后台任务中完成这项工作似乎并不是必需的,但这是最佳实践。
override init() {
super.init()
if WCSession.isSupported() {
session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let taskID = self.beginBackgroundUpdateTask()
//Do work here...
self.endBackgroundUpdateTask(taskID)
})
var replyValues = Dictionary<String, AnyObject>()
let status = "\(NSDate()): iPhone message: App received and processed a message: \(message)."
print(status)
replyValues["status"] = status
replyHandler(replyValues)
}
func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier {
return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})
}
func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) {
UIApplication.sharedApplication().endBackgroundTask(taskID)
}发布于 2015-08-27 17:30:34
在WatchKit扩展中,您将希望使用WatchConnectivity WCSession sendMessage API。在扩展部分中,检查是否可以访问iOS应用程序,然后发送消息:
let session = WCSession.defaultSession();
if session.reachable {
let message = ["foo":"bar"]
session.sendMessage(message, replyHandler: nil, errorHandler: { (error) -> Void in
print("send failed with error \(error)")
})
}此消息将导致系统在后台唤醒iOS应用程序,因此确保在运行在后台时调用的iOS应用程序代码中设置WCSession (例如:您不希望将其放入UIViewController的子类的viewDidLoad中,以便接收消息。由于您将请求一些信息,您可能希望利用答复块。
这就是在后台启动iOS应用程序的方法,尽管WatchConnectivity WWDC会话建议在可能的情况下使用“背景”传输方法。如果你的手表应用程序是只读的,那么你应该可以在iOS设备上使用背景传输排队等待任何更改,然后它们将在下次运行时交付给手表应用程序。
https://stackoverflow.com/questions/31618550
复制相似问题