HealthKit 后台交付是否可以在未运行的情况下启动应用程序?特别是在终止状态?
3 回答
经过一整天的测试(iOS 9.2),我可以确认HealthKit
后台交付在以下所有应用程序状态下都有效:
- 背景(在后台和执行代码中),
- 暂停(在后台但不执行代码),
- 终止(由用户强制终止或由系统清除)。
请记住:第 1 部分
某些HealthKit
数据类型的最小更新频率为HKUpdateFrequencyHourly
. 也就是说,即使您设置了频率的后台交付HKUpdateFrequencyImmediate
,您也不会比每小时左右更频繁地获得更新。
不幸的是,文档中没有关于每种数据类型的最小频率的信息,但我的经验Fitness types
如下:
- 有功能量:每小时,
- 骑行距离:立即,
- 爬升的航班:立即,
- NikeFuel:立即,
- 步骤:每小时,
- 步行+跑步距离:每小时,
- 锻炼:立即。
注意:immediate
并不意味着实时,而是“不久之后”活动数据样本已写入HealthKit
数据库/存储。
请记住:第 2 部分
如果设备被密码锁定,则不会调用任何后台交付观察员。由于隐私问题,这是故意的(阅读更多:https ://developer.apple.com/library/ios/documentation/HealthKit/Reference/HealthKit_Framework/ )。
也就是说,一旦用户解锁设备,您的 HealthKit
后台交付观察者就会被调用(当然,如果最低频率时间已经过去)。
示例代码:
看看 Viktor Sigler 的回答。HealthKit
虽然,您可以从他的答案开始跳过所有三个步骤,因为后台交付工作不需要它们。
这个答案有些晚了,但我希望这有助于人们了解如何HKObserverQuery
成功地使用。
首先,HKObserverQuery
在后台模式和应用程序完全关闭时工作正常。但是您需要先设置一些选项以使一切正常。
- 您需要在应用程序的功能中设置背景模式。见下图:
- 然后你需要
Required Background Modes
在你info.plist
的中添加如下图所示:
您需要通过
Background Fetch
以下方式设置:3.1。从方案工具栏菜单中,选择一个 iOS 模拟器或设备。
3.2. 从同一菜单中,选择编辑方案。
3.3. 在左列中,选择运行。
3.4. 选择选项选项卡。
3.5. 选中背景提取复选框,然后单击关闭。
然后,当应用程序处于后台或关闭时,您可以使用以下代码接收通知:
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 授权,则激活通知,然后激活通知。
我希望这对你有帮助。
在 iOS 8.1 中确实如此。不过,您需要确保在应用程序委托中重新创建观察者查询application:didFinishLaunchingWithOptions:
。8.0 中的一个错误阻止了 HealthKit 的后台通知工作。
编辑:
在您的AppDelegate中:
- (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];
}