HealthKit背景传递能否在应用程序未运行时启动应用程序?特别是在终止状态下?
HealthKit背景传递能否在应用程序未运行时启动应用程序?特别是在终止状态下?
HealthKit
后台传递确实有效:
请记住:第1部分
某些HealthKit
数据类型有最小更新频率HKUpdateFrequencyHourly
。也就是说,即使您使用HKUpdateFrequencyImmediate
设置了后台传递,您也不会比每小时或更长时间更新更快。
不幸的是,文档中没有关于每种数据类型的最小频率的信息,但我的Fitness类型
经验如下:
注意:立即
并不意味着实时,而是“在活动数据样本被写入HealthKit
数据库/存储后不久”。
请记住:第2部分
如果设备使用密码锁定,则没有一个后台传递观察者会被调用。这是出于隐私考虑而有意为之。
话虽如此,但只要设备解锁,您的HealthKit
后台交付观察者将被调用,前提是已经过了最小频率时间。
示例代码
参考Viktor Sigler的答案,但是可以跳过他答案开头的三个步骤,因为这些步骤对于HealthKit
后台交付无需求。
HKObserverQuery
。
首先,HKObserverQuery
在后台模式和完全关闭应用程序时都可以正常工作。但是,您需要首先设置一些选项才能使所有内容正常工作。
info.plist
中添加Required Background Modes
:您需要按照以下方式设置Background Fetch
:
3.1. 从方案工具栏菜单中选择iOS模拟器或设备。
3.2. 从同一菜单中选择编辑方案。
3.3. 在左列中选择运行。
3.4. 选择选项卡。
3.5. 选择“Background Fetch”复选框,然后单击“关闭”。
然后,您可以使用以下代码在应用程序处于后台或关闭状态时接收通知:
import UIKit
import HealthKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let healthKitStore:HKHealthStore = HKHealthStore()
func startObservingHeightChanges() {
let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
var query: HKObserverQuery = HKObserverQuery(sampleType: sampleType, predicate: nil, updateHandler: self.heightChangedHandler)
healthKitStore.executeQuery(query)
healthKitStore.enableBackgroundDeliveryForType(sampleType, frequency: .Immediate, withCompletion: {(succeeded: Bool, error: NSError!) in
if succeeded{
println("Enabled background delivery of weight changes")
} else {
if let theError = error{
print("Failed to enable background delivery of weight changes. ")
println("Error = \(theError)")
}
}
})
}
func heightChangedHandler(query: HKObserverQuery!, completionHandler: HKObserverQueryCompletionHandler!, error: NSError!) {
// Here you need to call a function to query the height change
// Send the notification to the user
var notification = UILocalNotification()
notification.alertBody = "Changed height in Health App"
notification.alertAction = "open"
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
completionHandler()
}
func authorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!) {
// 1. Set the types you want to read from HK Store
let healthKitTypesToRead = [
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth),
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType),
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex),
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight),
HKObjectType.workoutType()
]
// 2. Set the types you want to write to HK Store
let healthKitTypesToWrite = [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned),
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning),
HKQuantityType.workoutType()
]
// 3. If the store is not available (for instance, iPad) return an error and don't go on.
if !HKHealthStore.isHealthDataAvailable() {
let error = NSError(domain: "any.domain.com", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
if( completion != nil ) {
completion(success:false, error:error)
}
return;
}
// 4. Request HealthKit authorization
healthKitStore.requestAuthorizationToShareTypes(Set(healthKitTypesToWrite), readTypes: Set(healthKitTypesToRead)) { (success, error) -> Void in
if( completion != nil ) {
dispatch_async(dispatch_get_main_queue(), self.startObservingHeightChanges)
completion(success:success,error:error)
}
}
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert | .Badge | .Sound, categories: nil))
self.authorizeHealthKit { (authorized, error) -> Void in
if authorized {
println("HealthKit authorization received.")
}
else {
println("HealthKit authorization denied!")
if error != nil {
println("\(error)")
}
}
}
return true
}
//Rest of the defaults methods of AppDelegate.swift
}
HKObserver
会在用户授权 HealthKit 并激活通知后被激活。 application:didFinishLaunchingWithOptions:
中重新创建观察者查询。由于8.0中存在错误,导致HealthKit的后台通知完全无法工作。- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//create/get your HKHealthStore instance (called healthStore here)
//get permission to read the data types you need.
//define type, frequency, and predicate (called type, frequency, and predicate here, appropriately)
UIBackgroundTaskIdentifier __block taskID = [application beginBackgroundTaskWithExpirationHandler:^{
if (taskID != UIBackgroundTaskInvalid) {
[application endBackgroundTask:taskID];
taskID = UIBackgroundTaskInvalid;
}
}];
[healthStore enableBackgroundDeliveryForType:type frequency:frequency withCompletion:^(BOOL success, NSError *error) {}];
HKQuery *query = [[HKObserverQuery alloc] initWithSampleType:healthType predicate:predicate updateHandler:
^void(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error)
{
//If we don't call the completion handler right away, Apple gets mad. They'll try sending us the same notification here 3 times on a back-off algorithm. The preferred method is we just call the completion handler. Makes me wonder why they even HAVE a completionHandler if we're expected to just call it right away...
if (completionHandler) {
completionHandler();
}
//HANDLE DATA HERE
if (taskID != UIBackgroundTaskInvalid) {
[application endBackgroundTask:taskID];
taskID = UIBackgroundTaskInvalid;
}
}];
[healthStore executeQuery:query];
}
didFinishLaunchingWithOptions:
中设置观察者。在您正在观察的类型的新数据事件中,HealthKit将在实际发送相关观察者的通知之前启动您的应用程序。通过在didFinishLaunchingWithOptions:
中设置观察者查询,您承诺在准备好观察者的同时通知您任何新数据。 https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKObserverQuery_Class/index.html#//apple_ref/doc/uid/TP40014747 - goldengil