天天看點

Watch OS 2.0 健身寵物app開發心得[1]-Healthkit的sdk接入Watch OS2 - Healthkit的sdk接入

Watch OS2 - Healthkit的sdk接入

部落客于今年7月底開始接觸watch os2.0系統,聽聞在os2.0上已經支援了原生app的開發,便興緻沖沖的開始了一段漫長的爬坑之旅! 部落客主要開發的項目是在watch上研發一款健身寵物養成類遊戲,如下圖:

Watch OS 2.0 健身寵物app開發心得[1]-Healthkit的sdk接入Watch OS2 - Healthkit的sdk接入

主要的功能就是利用watch os2.0 上的healkit sdk,依據watch收集的個人健康資料,以及完成這款原生app(即健身寵物,後文如此稱呼)所指定的鍛煉任務後,可以獲得鍛煉寵物的活力,以及捕捉相應各種種類的寵物等。而你所圈養的寵物的進化,也會依據主人的鍛煉成果而有所不同,分為肌肉型,智慧型,以及肥胖型。 是以由上述功能可知,開發這款健身寵物,其核心子產品就是apple watch上的healthkit sdk。 部落客開發的時候,使用的開發環境是Xcode 7.0 beta 5 ,watch os 2.0 以及 ios 9.0。 好了,言歸正傳,下面就來講述下部落客在搭建項目階段遇到的第一個坑,既是Healkit的sdk接入,所會遇見的最主要的問題。 首先,要導入apple提供的healthkit的sdk,你需要在你的項目工程檔案中的target下,找到ios targets以及watchkit extensition的Capabilities目錄,打開這兩者中的healthkit開關。具體位置如下圖所示:

Watch OS 2.0 健身寵物app開發心得[1]-Healthkit的sdk接入Watch OS2 - Healthkit的sdk接入

在打開了項目設定裡的ios 以及 watchkit extensition的healkit 開關後,我們将要進行下一步操作——請求healthkit 資料讀取的授權。網上有很多類似的使用案例,在此我也将我的使用方法貼出來,這裡不是重點,随後在appDelegate.swift中的設定才是重點。

import WatchKit
import Foundation
import HealthKit
import ClockKit

class ExtensionDelegate: NSObject, WKExtensionDelegate{
    let healthManager = HealthManager()
    let userDefault = NSUserDefaults.standardUserDefaults()
    let gameData = GameData.shareInstance()
    let csvReader = CSVReaderSingleton.shareInstance()
    
    func applicationDidFinishLaunching() {
        // Perform any final initialization of your application.
        initData()
        gameData.configData = GameData.getConfigDataFromCSV(9000)
        if !userDefault.boolForKey("firstLogin") {
            firstInit()
            gameData.setUserData()
        }
        gameData.getUserData()
    }

    func applicationDidBecomeActive() {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        gameData.getUserData()
        gameData.startBenefitTimer()
        gameData.checkPetReward()
        gameData.checkFatAdding()
        gameData.checkHealthReward()
        
        gameData.startWorkSession()
    }

    func applicationWillResignActive() {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, etc.
        gameData.setUserData()
        gameData.closeBenefitTimer()
        gameData.endWorkSession()
//        refreshComplications()
    }
    
    func didReceiveLocalNotification(notification: UILocalNotification) {
        
    }
    
    func firstInit() {
        // --- 标示使用者是否為首次登陸
        userDefault.setBool(true, forKey: "firstLogin")
        gameData.currentPetData.id = gameData.configData.defaultPet
        gameData.currentPlayerData.storeItemUsing = gameData.configData.defaultTrain
        gameData.currentPlayerData.storeItemPurchased.append(gameData.configData.defaultTrain)
    }
    
    func initData() {
        // --- 初始化csv資料
        csvReader.initDictionaryData()
        // --- 請求healthkit授權
        print("start request authorize")
        healthManager.authorizeHealthKit { (authorized,  error) -> Void in
            if authorized {
                print("HealthKit authorization received.")
            }
            else{
                print("HealthKit authorization denied!")
                if error != nil {
                    print("\(error)")
                }
            }
        }
    }
    
    func refreshComplications() {
        let clockServer = CLKComplicationServer.sharedInstance()
        for complication in clockServer.activeComplications
        {
            if complication.family == .ModularLarge
            {
                // refresh the complication datas
                clockServer.extendTimelineForComplication(complication)
            }
        }
    }
}
           

在watchkit Extensition上擷取了授權後(即watch取得授權),還需要向手機進行一次healthkit的授權驗證(無法避免)。這就是很多人容易忽略掉的一步,缺少了這一步,apple watch是無法獲得healthkit中心的資料的。是以,我們需要在ios的工程中的AppDelegate.swift中加入如下一句話:(如圖)

Watch OS 2.0 健身寵物app開發心得[1]-Healthkit的sdk接入Watch OS2 - Healthkit的sdk接入

在此處對手機進行授權通路驗證後,才能使apple watch 的healthkit 資料授權成功。

好了,第一篇主要是将healthkit的接入,下一篇部落格,部落客将具體介紹如何實作 心跳資料的讀取,以及脈搏跳動動畫,并分享一下apple watch上按小時分鐘擷取healthkit step資料的所遇到的大坑,以及如何填補這個坑。

繼續閱讀