gpt4 book ai didi

iphone - watchOS2 应用程序和 iPhone 应用程序通信

转载 作者:行者123 更新时间:2023-12-03 20:50:52 25 4
gpt4 key购买 nike

在watchOS1中,我们有一个方法“openParentApplication”。即使手机应用程序没有在前台或后台运行,此方法也会与手机应用程序进行通信并立即获取回复。我需要类似的 watchOS2。我希望我的 watch 应用程序能够立即与手机应用程序通信,即使我的 iPhone 应用程序没有运行。 updateApplicationContext:error:sendMessage:replyHandler:errorHandler:transferUserInfo: 等方法在这种情况下没有帮助。

请问有人可以建议我更好的方法来实现这一目标吗?

最佳答案

实际上 sendMessage:replyHandler:errorHandler: 正在执行您所要求的操作。只要您的 watch 连接到手机,它就会立即收到对该消息的回复。当应用程序位于前台、后台或根本不运行时,此功能有效。

设置方法如下:

在 WatchExtension 中:

设置 session 。通常在您的 ExtensionDelegate 中:

func applicationDidFinishLaunching() {
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
}

然后当您需要应用程序中的某些内容时发送消息:

if WCSession.defaultSession().reachable {
let messageDict = ["message": "hello iPhone!"]
WCSession.defaultSession().sendMessage(messageDict, replyHandler: { (replyDict) -> Void in
print(replyDict)
}, errorHandler: { (error) -> Void in
print(error)
}
}

在 iPhone 应用程序中:

相同的 session 设置,但这次还设置了委托(delegate):

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
}

然后实现委托(delegate)方法将回复发送到 watch :

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
replyHandler(["message": "Hello Watch!"])
}

只要 Watch 和 iPhone 之间存在连接,此功能就会起作用。如果应用程序未运行,系统会在后台启动它。所以,基本上它的工作原理就像 openParentApplication(_:reply:)

关于iphone - watchOS2 应用程序和 iPhone 应用程序通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com