【发布时间】:2015-10-21 19:15:03
【问题描述】:
一些详细介绍 Watch Connectivity 的优秀博客文章(http://www.kristinathai.com/watchos-2-tutorial-using-application-context-to-transfer-data-watch-connectivity-2/ 和 http://natashatherobot.com/watchconnectivity-application-context/)使用简单的应用示例,当您在 iPhone 上点击 UI 时将数据发送到手表。
我的应用程序只是列出了我的 iPhone 应用程序中的数据,所以我不需要立即发送数据,我只是想在应用程序加载或进入后台时发送它......为此我做了@ didFinishLaunching 和 didEnterBackground 中的 987654323@ ......但是我的手表界面控制器中的 dataSource 委托非常容易被触发......特别是一瞥只加载在模拟器上,从不加载到设备上。有更好的时间和地点推送信息吗?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
WatchSessionManager.sharedManager.startSession()
do {
try WatchSessionManager.sharedManager.updateApplicationContext(["peopleDict" : peopleDict])
} catch {
print(error)
}
return true
}
func applicationDidEnterBackground(application: UIApplication) {
do {
try WatchSessionManager.sharedManager.updateApplicationContext(["peopleDict" : peopleDict])
} catch {
print(error)
}
}
下面是我的WatchSessionManager 我曾经在我的extensionDelegate 的appliciationDidFinishLaunching 中调用activiateSession
import WatchConnectivity
protocol DataSourceChangedDelegate {
func dataSourceDidUpdate(dataSource: DataSource)
}
class WatchSessionManager: NSObject, WCSessionDelegate {
static let sharedManager = WatchSessionManager()
private override init() {
super.init()
}
private var dataSourceChangedDelegates = [DataSourceChangedDelegate]()
private let session: WCSession = WCSession.defaultSession()
func startSession() {
session.delegate = self
session.activateSession()
}
func addDataSourceChangedDelegate<T where T: DataSourceChangedDelegate, T: Equatable>(delegate: T) {
dataSourceChangedDelegates.append(delegate)
}
func removeDataSourceChangedDelegate<T where T: DataSourceChangedDelegate, T: Equatable>(delegate: T) {
for (index, indexDelegate) in dataSourceChangedDelegates.enumerate() {
if let indexDelegate = indexDelegate as? T where indexDelegate == delegate {
dataSourceChangedDelegates.removeAtIndex(index)
break
}
}
}
}
// MARK: Application Context
// use when your app needs only the latest information
// if the data was not sent, it will be replaced
extension WatchSessionManager {
// Receiver
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self?.dataSourceChangedDelegates.forEach { $0.dataSourceDidUpdate(DataSource(data: applicationContext))}
}
}
}
【问题讨论】:
标签: ios swift watchkit apple-watch watchconnectivity