編輯:關於 Android 程式設計
根據媒體報導,健康與健美在當今的重要性可說是空前。說來有趣,似乎就在幾天前,筆者還看過類似的新聞——或許這是每個人隨年紀漸長而揮之不去的念頭吧:渴望維持健康、保持體態。無論如何,健康始終是個不容小覷的話題。而技術的進步,尤其是行動應用與硬體的不斷演進,正為這個日益火熱的領域帶來全新契機。
HealthKit 是蘋果推出的行動平台,旨在為重要且可追蹤的健康數據,與注重健康、熱衷健身的科技使用者之間搭起橋樑。這點子很酷——使用者能輕鬆追蹤一段時間內可量測的健身與健康指標。除了掌握自身數據,看著圖表上那道上升的曲線,本身就是一種激勵。
正如你想像的那樣,在處理健康資訊時,隱私是極關鍵的一環。HealthKit 把健康資料的絕對控制權交還到使用者手中:使用者可以授權,也可以拒絕任何應用讀取自己的健康數據。
身為開發者,我們需要徵求許可才能從 HealthKit 讀取或寫入數據,而且必須明確聲明打算讀寫哪些項目。此外,任何採用 HealthKit 的應用都必須附上隱私政策,好讓使用者對自己的資訊處理方式更安心。
在本文中,我們將動手打造一個有趣的小應用,它會從 HealthKit 讀取數據,也會寫入新數據。來認識一下 OneHourWalker 吧。

OneHourWalker 是一款追蹤使用者在一小時內行走或跑步距離的健身應用。使用者可以將距離分享給 HealthKit,之後便能於健康應用中讀取。我知道,一小時聽起來或許有點過於樂觀(至少筆者本人大概堅持不了),所以使用者也能提前結束計時並分享已走距離。
咦,說到這裡,OneHourWalker 似乎只會向 HealthKit 寫入數據。那我們到底要讀取什麼呢?點此下載 OneHourWalker 的初始專案,先跑起來感受一下應用的運作。計時器與位置追蹤功能已經就緒,因此我們只需專心處理 HealthKit 的實作。請留意,當時間到達 60 分鐘時,計時與追蹤都會停止。
首先,在我們的應用中啟用 HealthKit。在專案導航中點擊 OneHourWalker,接著點擊 Targets 下的 OneHourWalker,然後選擇畫面上方的 Capabilities 選項。

捲到 Capabilities 列表底部,啟用 HealthKit。這個簡單的動作會自動把 HealthKit 權限加入 App ID、在 info plist 中新增 HealthKit 鍵、把權限寫入授權檔,並連結 HealthKit.framework。就這麼輕鬆。
接著跳到 TimerViewController.swift,開始把 HealthKit 引入 OneHourWalker。第一步,建立一個 HealthKitManager 實例。
import UIKit import CoreLocation import HealthKit class TimerViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var milesLabel: UILabel! @IBOutlet weak var heightLabel: UILabel! var zeroTime = NSTimeInterval() var timer : NSTimer = NSTimer() let locationManager = CLLocationManager() var startLocation: CLLocation! var lastLocation: CLLocation! var distanceTraveled = 0.0 let healthManager:HealthKitManager = HealthKitManager()
所有 HealthKit 相關的工作都會在 HealthKitManager.swift 中進行,它會封裝幾個關鍵方法,稍後我們會逐一談到。
正如開頭所述,我們得先取得使用者許可,才能讀寫他們的健康數據。這一步在 viewDidLoad() 中完成。
override func viewDidLoad() { super.viewDidLoad() locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled(){ locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest } else { print("Need to Enable Location") } // We cannot access the user's HealthKit data without specific permission. getHealthKitPermission() }
getHealthKitPermission() 方法會呼叫 manager 的 authorizeHealthKit()。若一切順利,我們就能接著呼叫 setHeight(),這個方法稍後再細說。
func getHealthKitPermission() { // Seek authorization in HealthKitManager.swift. healthManager.authorizeHealthKit { (authorized, error) -> Void in if authorized { // Get and set the user's height. self.setHeight() } else { if error != nil { print(error) } print("Permission denied.") } } }
在 HealthKitManager.swift 中,我們建立 authorizeHealthKit() 方法。除此之外,還需要建立 HealthKit 儲存庫,用來串接應用與 HealthKit 的數據。
let healthKitStore: HKHealthStore = HKHealthStore() func authorizeHealthKit(completion: ((success: Bool, error: NSError!) -> Void)!) { // State the health data type(s) we want to read from HealthKit. let healthDataToRead = Set(arrayLiteral: HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!) // State the health data type(s) we want to write from HealthKit. let healthDataToWrite = Set(arrayLiteral: HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!) // Just in case OneHourWalker makes its way to an iPad... if !HKHealthStore.isHealthDataAvailable() { print("Can't access HealthKit.") } // Request authorization to read and/or write the specific data. healthKitStore.requestAuthorizationToShareTypes(healthDataToWrite, readTypes: healthDataToRead) { (success, error) -> Void in if( completion != nil ) { completion(success:success, error:error) } } }
在請求健康數據授權時,我們必須明確指定要讀取與修改的項目。就本例而言,我們要讀取使用者身高,好幫他們避開頭頂的低垂枝丫;我們期望 HealthKit 提供一個能轉換成可讀身高的 HKObject 量。此外,我們也要取得修改 HKObject 量的權限,以記錄行走與跑步的距離。
在妥善處理 OneHourWalker 與 iPad 溝通的潛在情況後,我們正式發出請求。
在 HealthKitManager.swift 中,建立從 HealthKit 讀取使用者身高的 getHeight() 方法。
func getHeight(sampleType: HKSampleType , completion: ((HKSample!, NSError!) -> Void)!) { // Predicate for the height query let distantPastHeight = NSDate.distantPast() as NSDate let currentDate = NSDate() let lastHeightPredicate = HKQuery.predicateForSamplesWithStartDate(distantPastHeight, endDate: currentDate, options: .None) // Get the single most recent height let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) // Query HealthKit for the last Height entry. let heightQuery = HKSampleQuery(sampleType: sampleType, predicate: lastHeightPredicate, limit: 1, sortDescriptors: [sortDescriptor]) { (sampleQuery, results, error ) -> Void in if let queryError = error { completion(nil, queryError) return } // Set the first HKQuantitySample in results as the most recent height. let lastHeight = results!.first if completion != nil { completion(lastHeight, nil) } } // Time to execute the query. self.healthKitStore.executeQuery(heightQuery) }
查詢身高資料的第一步,是建立一個斷言來定義時間範圍——我們要的是一段很長時間內的所有身高記錄(從一個距今甚遠的過去日期到現在)。顯然這會回傳一個陣列,但我們只想要最近一次的身高,因此在請求時可以讓最新的資料排在陣列最前面。
在構建查詢時,我們把陣列長度限制為 1。考慮到出錯的可能後,我們把結果中首個、也是唯一一筆資料指派給 lastHeight。接著完善 getHeight() 方法,最後針對使用者的健康數據執行查詢。
回到 TimerViewController.swift,在應用正式啟用前,假設使用者已授予相應權限,setHeight() 便會由 getHealthKitPermission() 呼叫。
var height: HKQuantitySample?
首先,我們需要為 HKQuantitySample 實例宣告一個身高變數。
func setHeight() { // Create the HKSample for Height. let heightSample = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight) // Call HealthKitManager's getSample() method to get the user's height. self.healthManager.getHeight(heightSample!, completion: { (userHeight, error) -> Void in if( error != nil ) { print("Error: \(error.localizedDescription)") return } var heightString = "" self.height = userHeight as? HKQuantitySample // The height is formatted to the user's locale. if let meters = self.height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) { let formatHeight = NSLengthFormatter() formatHeight.forPersonHeightUse = true heightString = formatHeight.stringFromMeters(meters) } // Set the label to reflect the user's height. dispatch_async(dispatch_get_main_queue(), { () -> Void in self.heightLabel.text = heightString }) }) }
我們在 share() 方法之上建立 setHeight()。所請求的身高樣本以 HKQuantity 形式回傳,由標識符 HKQuantityTypeIdentifierHeight 辨識該物件。
接著呼叫 manager 中建立的 getHeight() 方法。有了身高樣本後,我們還得把它轉譯成合適的字串,才能顯示在標籤上。一如既往,妥善處理各種可能的錯誤很重要。
至此,使用者便能打開應用,查看自己的身高(若其健康應用中存有身高資料),啟動計時器,追蹤行走或跑步的距離了。接下來,我們要處理把距離數據寫入健康應用的流程,如此使用者才能在同一個應用中保存所有健身數據。
當使用者結束戶外鍛鍊後,不論是否滿 60 分鐘,都可能會按下 Share 按鈕,把辛苦累積的運動距離傳送到健康應用。因此,在 share() 方法中,我們需要呼叫 HealthKitManager.swift 的 saveDistance() 方法來完成這件事。在這個方法裡,我們會送出運動距離以及取得該距離的日期,這樣使用者隔天便能挑戰更好的成績。
@IBAction func share(sender: AnyObject) { healthManager.saveDistance(distanceTraveled, date: NSDate()) }
接著回到 manager,在此建立 saveDistance() 方法。首先,我們讓 HealthKit 知道要寫入一個代表步行與跑步距離的量;接著把度量單位設為英里,並賦予正式的樣本量。最後由 HealthKit 的 saveObject() 方法把資料寫入使用者的健康數據。
func saveDistance(distanceRecorded: Double, date: NSDate ) { // Set the quantity type to the running/walking distance. let distanceType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning) // Set the unit of measurement to miles. let distanceQuantity = HKQuantity(unit: HKUnit.mileUnit(), doubleValue: distanceRecorded) // Set the official Quantity Sample. let distance = HKQuantitySample(type: distanceType!, quantity: distanceQuantity, startDate: date, endDate: date) // Save the distance quantity sample to the HealthKit Store. healthKitStore.saveObject(distance, withCompletion: { (success, error) -> Void in if( error != nil ) { print(error) } else { print("The distance has been recorded! Better go check!") } }) }
跳到健康應用,所記錄的數據會出現在 Walking + Running Distance(行走+跑步距離)那一列(前提是已啟用)。此外,依下列路徑還能看到詳細的樣本數據:Health Data tab(健康數據分頁) > Fitness(健身) > Walking + Running Distance(行走+跑步距離) > Show All Data(顯示所有數據)。我們的數據就在這個列表中。輕點某一筆,我們的圖示(目前尚未設定)就會與距離一同出現;再次點擊,便能看見完整的細節。

透過 OneHourWalker,我們便能為全球 iOS 使用者的身體健康盡一份心力。不過,這僅僅是個開始——在讀寫健康數據這條路上,還有無比遼闊的可能性。
當然,對使用者而言,擁有這些可追蹤的數據好處多多:人們能輕鬆地按日期、按星期進行比較,激勵自己朝目標邁進。而真正偉大之處在於,開發者能提供全新、富有創意的有趣方式來運用這些數據。
歡迎大家動手測試這款 HealthKit 應用,也別忘了查看 OneHourWalker 的最終版本。
Android 使用環信 SDK 開發即時通訊功能的整合重點
為何選擇環信 SDK在 Android 應用中導入即時聊天功能時,開發者通常會評估介面是否簡潔、文件是否清楚、是否支援 Android、iOS 與後端服務。環信 SDK
Android 插件化基礎(4):動態啟動插件中的 Activity
Android 插件化基礎(4)——動態啟動插件中的 Activity 作者:鄭海波-莫川 簡介 如何動態啟動插件中的 Activity?我們先分析需要做好哪些準備: 1
RxJava 菜鳥驛站(一):核心概念與執行緒控制
RxJava 是以可觀察序列組建異步與事件式程式的 Java 函式庫。它的核心概念是 Observable、Observer、subscribe 與事件流,並透過 Sch
用阿里大魚(AliDayu)實作手機簡訊驗證碼
先說結論:整體流程 想幫 App 或網站加上「手機簡訊驗證碼」其實不難,阿里大魚(AliDayu,官網 https://www.alidayu.com/)提供的免費/低價