您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

WatchConnectivity 實作:用 Application Context 同步最新資料

編輯:iOS 開發基礎

譯者:鋼鐵俠般的卿哥(微博)

原文:WatchConnectivity: Sharing The Latest Data via Application Context


還沒掌握 WatchOS 2 的同學,可以先參考先前已發布的幾篇文章:

  • WatchOS 2: Hello, World

  • WatchConnectivity Introduction: Say Goodbye To The Spinner

  • WatchConnectivity: Say Hello to WCSession

當你的 Watch App 只需要展示「最新可用」的資訊時,就能透過 Application Context 傳輸後台資料。舉例來說,如果你的 Glance 顯示比賽比分,使用者並不關心兩分鐘前 4-2 的舊分數,他們只在乎當前是 4-4;又比如交通類 App,使用者不關心上上五分鐘開走的那班巴士,他們只想知道下一班車何時到來。

所以 Application Context 的運作方式是:把分片的資料插入佇列,如果在資料被傳送前又產生了全新的資料,那麼原來的舊資料就會被新資料取代,如此反覆,直到有新資料再次取代它。

本文靈感來自 Kristina Thai 的 Application Context 教程。我將打造一個類似、以 emoji 為主題的 app。在我的 app 裡,使用者從 iPhone 選單中選擇食物 emoji,最新的食物選項便會呈現在 Apple Watch app 上。

免責聲明

請注意,在我的 app 中,我會寫得比 Kristina 的教程更多的抽象資料更新模型,因此這個示範 demo 會顯得有些「過度設計」。

如果你的真實 app 規模比這更大,需要透過 iOS app(或 Watch app)接收並更新許多視圖或資料源,那麼這種抽象就有意義。但假如你的 app 就像我示範的這麼簡單、只有一個視圖要更新,那還是保持簡單,直接研究 Kristina 的教程即可。

我也在嘗試用不同方式撰寫抽象層,把更新資料送到 app 所需的不同部分,所以我相信會有更好的實作方式。若你有任何想法,歡迎在評論中告訴我。

前置步驟

關於這個教程,我假設你已經知道如何在 Xcode 中建立一個單視圖應用,以及如何建立一個簡單的食物 emoji 列表視圖;若有疑問,請參考我的 FoodSelectionViewController。

我也假設你了解如何建立一個 Watch App,並在 Interface.Storyboard 中設定基礎樣式;若需要這方面的協助,請閱讀我的 WatchOS 2: Hello, World 教程。

最後,你應該能夠建立一個基礎的單例來封裝 WCSession,並在 AppDelegate 的 application:didFinishLaunchingWithOptions: 方法與 Watch Extension 的 ExtensionDelegate 的 applicationDidFinishLaunching 方法中啟用它;若有疑問,請看我的 WatchConnectivity: Say Hello to WCSession 教程。

在你的 iOS app 中有如下程式碼:

  // in your iOS app   import WatchConnectivity class WatchSessionManager: NSObject, WCSessionDelegate {     static let sharedManager = WatchSessionManager()     private override init() {         super.init()     }      private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil      private var validSession: WCSession? {         // paired - the user has to have their device paired to the watch         // watchAppInstalled - the user must have your watch app installed          // Note: if the device is paired, but your watch app is not installed         // consider prompting the user to install it for a better experience          if let session = session where session.paired && session.watchAppInstalled {                 return session             }         return nil             }      func startSession() {         session?.delegate = self         session?.activateSession()     } }

在你的 Watch App 中有如下程式碼:

// in your WatchKit Extension import WatchConnectivity class WatchSessionManager: NSObject, WCSessionDelegate {     static let sharedManager = WatchSessionManager()     private override init() {         super.init()     }     private let session: WCSession = WCSession.defaultSession()     func startSession() {         session.delegate = self         session.activateSession()     } }

當然,若你需要更多說明,可以參考本教程的源碼。

傳送資料

在我的應用裡,當使用者選擇一項食物選項時,它就會在後台被傳輸到我的 Watch App。這裡 iOS 應用是傳送方,而且實作起來非常容易。

只需在你的 iOS app 中擴充 WatchSessionManager 單例來更新 application context:

// in your iOS app // MARK: Application Context // use when your app needs only the latest information // if the data was not sent, it will be replaced extension WatchSessionManager {     // This is where the magic happens!     // Yes, that's it!      // Just updateApplicationContext on the session!     func updateApplicationContext(applicationContext: [String : AnyObject]) throws {         if let session = validSession {                         do {                             try session.updateApplicationContext(applicationContext)                         } catch let error {                             throw error                         }             }     } }

現在當使用者選擇一項食物欄時,你需要呼叫以下方法:

就是這樣!食物項已經進入佇列,將會被發送到你的 Watch App——除非在它被傳送前,使用者又選了新的食物選項。

接收資料

你的 Watch App 現在需要接收資料,這同樣很簡單,只要實作 WCSessionDelegate 中的 session:didReceiveApplicationContext: 方法即可。

// in your Watch App // MARK: Application Context // use when your app needs only the latest information // if the data was not sent, it will be replaced extension WatchSessionManager {     // Receiving data     func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {         // update data here         // this will be filled in in the Updating Data Section below!     } }

更新資料

現在你收到了資料,然而棘手的部分來了:設法讓你的 Watch Extension 的 InterfaceController 及其他視圖或資料源知道資料已經更新。一種方法是透過 NSNotificationCenter,但我將嘗試一個不同的方式。這個部分可以用多種方法實現,而且對這個 app 來說確實有些過度設計,請記住這一點。

自從使用 Swift,我的目標是改變模型的型別。不幸的是,正如我在部落格中關於 WCSession 的文章所提到的,WCSessionDelegate 只能以 NSObject 的子類來實作。為了相容上述限制,我建立了一個既能承載 applicationContext 資料、又能轉換為不可變型別、還能被多個視圖控制器共享的資料源。

// in your WatchKit Extension struct DataSource {     let item: Item          enum Item {         case Food(String)         case Unknown     }      init(data: [String : AnyObject]) {         if let foodItem = data["food"] as? String {                         item = Item.Food(foodItem)             } else {                 item = Item.Unknown             }         } }

接著我定義一個協議,用來通知所有需要更新的部分,而這些部分需要知道最新的更新資料。

// in your WatchKit Extension //  WatchSessionManager.swift protocol DataSourceChangedDelegate {     func dataSourceDidUpdate(dataSource: DataSource) }

來到有趣的部分!你的 WatchSessionManager 需要追蹤所有的 dataSourceChangedDelegate,這要透過一個陣列來實現。addDataSourceChangedDelegate 方法會把 delegate 加入陣列,removeDataSourceChangedDelegate 則會把 delegate 從陣列中移除。

// in your WatchKit Extension //  WatchSessionManager.swift class WatchSessionManager: NSObject, WCSessionDelegate {     static let sharedManager = WatchSessionManager()     private override init() {         super.init()     }      private let session: WCSession = WCSession.defaultSession()      // keeps track of all the dataSourceChangedDelegates     private var dataSourceChangedDelegates = [DataSourceChangedDelegate]()       func startSession() {         session.delegate = self         session.activateSession()     }      // adds / removes dataSourceChangedDelegates from the array     func addDataSourceChangedDelegate(delegate: T) {         dataSourceChangedDelegates.append(delegate)     }      func removeDataSourceChangedDelegate(delegate: T) {         for (index, dataSourceDelegate) in dataSourceChangedDelegates.enumerate() {             if let dataSourceDelegate = dataSourceDelegate as? T where dataSourceDelegate == delegate {                 dataSourceChangedDelegates.removeAtIndex(index)                 break             }         }     } }

現在我們可以加入接收 application context 的實作了:

// in your WatchKit Extension //  WatchSessionManager.swift // 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))}             }     } }

現在我們只需確保 InterfaceController 遵循 DataSourceChangedDelegate,並被 WatchSessionManager 追蹤。

//  in your WatchKit Extension //  InterfaceController.swift import WatchKit class InterfaceController: WKInterfaceController, DataSourceChangedDelegate {     @IBOutlet var foodLabel: WKInterfaceLabel!     override func awakeWithContext(context: AnyObject?) {                  super.awakeWithContext(context)         // add InterfaceController as a dataSourceChangedDelegate         WatchSessionManager.sharedManager.addDataSourceChangedDelegate(self)     }      override func didDeactivate() {                  // remove InterfaceController as a dataSourceChangedDelegate         // to prevent memory leaks         WatchSessionManager.sharedManager.removeDataSourceChangedDelegate(self)          super.didDeactivate()     }      // MARK: DataSourceUpdatedDelegate     // update the food label once the data is changed!     func dataSourceDidUpdate(dataSource: DataSource) {         switch dataSource.item {         case .Food(let foodItem):                         foodLabel.setText(foodItem)         case .Unknown:             foodLabel.setText("ˉ\\_(ツ)_/ˉ")         }     } }

大功告成!

你可以到 GitHub 上查看完整源碼。特別感謝 @allonsykraken 對程式碼進行審核並提供建議。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved