在我的viewController中,我有一个AVAudioPlayer的变量
var audioPlayer = AVAudioPlayer()
我想在我的watchKit应用程序中访问此变量,以便我可以从watchKit应用程序播放和暂停AVAudioPlayer。像
audioPlayer.play()
audioPlayer.pause()
如何从watchKit应用程序中获取此变量?谢谢您的帮助!我正在使用Swift 3和Xcode 8。
答案 0 :(得分:1)
自watchOS 2起,您无法使用AppGroups直接在iOS应用和WatchKit应用之间共享数据。
两者之间进行通信的唯一选择是WatchConnectivity框架。使用WatchConnectivity,您可以使用即时消息发送iOS应用程序以开始/停止播放。在AppDelegate的iOS上实现类似这样的东西:
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
if let content = message["play"] as? [String:Any] {
audioPlayer.play()
replyHandler(["startedPlaying":true])
} else if let content = message["pause"] as? [String:Any] {
audioPlayer.pause()
replyHandler(["pausedMusic":true])
}
}
在您的Watch应用中,您需要发送包含AppDelegate session(_:didReceiveMessage:replyHandler:)
中指定内容的邮件。如果您不需要将回复发送回Watch应用,则可以使用session(_:didReceiveMessage:)
并删除replyHandler
部分。