ios - 已授予 HealthKit 授权并在模拟器上工作,但不在实际设备上工作

标签 ios swift watchkit healthkit

我正在为 Apple Watch 开发健身应用程序,但在我的实际 watch 上使用 HealthKit 时遇到了一些问题。

请求授权在模拟器和我的设备上都有效,并且在每次启动时都显示为成功。然而,查询和读取样本在我的设备上失败了,但在模拟器上却没有。

启动后,授权成功,需要查询或保存锻炼时提示“授权未确定”。

两个权利都已将 HealthKit 设置为 YES,HealthKit 和后台功能已打开,NSHealthShareUsageDescription 和 NSHealthUpdateUsageDescription key 在 iOS Info.plist 中提供。

授权码

// Configure write values
    let writeTypes: Set<HKSampleType> = [.workoutType(),
                                         HKSampleType.quantityType(forIdentifier: .heartRate)!,
                                         HKSampleType.quantityType(forIdentifier: .activeEnergyBurned)!,
                                         HKSampleType.quantityType(forIdentifier: .stepCount)!,
                                         HKSampleType.quantityType(forIdentifier: .distanceCycling)!,
                                         HKSampleType.quantityType(forIdentifier: .distanceSwimming)!,
                                         HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning)!,
                                         HKSampleType.quantityType(forIdentifier: .swimmingStrokeCount)!]
    // Configure read values
    let readTypes: Set<HKObjectType> = [.activitySummaryType(), .workoutType(),
                                        HKObjectType.quantityType(forIdentifier: .heartRate)!,
                                        HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
                                        HKObjectType.quantityType(forIdentifier: .stepCount)!,
                                        HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
                                        HKObjectType.quantityType(forIdentifier: .distanceSwimming)!,
                                        HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!,
                                        HKObjectType.quantityType(forIdentifier: .swimmingStrokeCount)!]

    // Create health store
    let healthStore = HKHealthStore()

    // Use it to request authorization for our types
    healthStore.requestAuthorization(toShare: writeTypes, read: readTypes) { (success, error) in
        if success {
            print("Success: authorization granted")
        } else {
            print("Error: \(error?.localizedDescription ?? "")")
        }
    }

查询代码(Udemy类(class))

func startQuery(_ quantityTypeIdentifier: HKQuantityTypeIdentifier) {
    // We only want data points after our workout start date
    let datePredicate = HKQuery.predicateForSamples(withStart: workoutStartDate, end: nil, options: .strictStartDate)
    // And from our current device
    let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
    // Combine them
    let queryPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [datePredicate, devicePredicate])
    // Write code to receive results from our query
    let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = { query, samples, deletedObjects, queryAnchor, error in

        //safely typecast to a quantity sample so we can read values
        guard let samples = samples as? [HKQuantitySample] else { return }

        //process the samples
        print("Start processing samples")
        self.process(samples, type: quantityTypeIdentifier)
    }

    // Create the query out of our type (e.g. heart rate), predicate and result handling code
    let quantityType = HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!
    let query = HKAnchoredObjectQuery(type: quantityType, predicate: queryPredicate, anchor: nil, limit: HKObjectQueryNoLimit, resultsHandler: updateHandler)

    // Tell HealthKit to re-run the code every time new data is available
    query.updateHandler = updateHandler

    // Start the query running
    healthStore.execute(query)

    // Stach it away so we can stop it later
    activeDataQueries.append(query)
}

最佳答案

我将授权代码放在我的 ExtensionDelegate 中,而不是我正在查询的同一个文件中,它开始工作。

之前它在模拟器上运行但在实际设备上运行不正常,这仍然很奇怪。

关于ios - 已授予 HealthKit 授权并在模拟器上工作,但不在实际设备上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033336/

相关文章:

ios - 如何使用界面生成器重叠 iOS watch 套件中的两个控件

ios - WatchOS 并发症 : is it possible to use custom text alignment?

ios - 在 Watch App 中创建进度圈作为 WKInterfaceImage

ios - 我正在尝试在没有Pod的项目中实现Afnetworking,只是将文件复制粘贴到我的项目中,但无法正常工作

swift - 如何像目录树一样向 NSOutlineView 上的节点添加更多节点?

ios - 如何防止导航到 UIViewController 检查条件?

swift - 设置 WatchKit 计时器的倒计时间隔

ios - 如何快速将json传递给服务器

ios - 我想在 ios 中每五分钟加载一次 facebook 插页式广告(swift)

ios - 当我运行我的应用程序时,是否有快捷方式可以知道我位于哪个 View Controller 中?