简体   繁体   English

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

[英]HealthKit authorization granted and working on simulator but not on actual device

I'm working on a workout app for the Apple Watch and ran into some problems using HealthKit on my actual watch. 我正在为Apple Watch开发健身应用程序,并在我的实际手表上使用HealthKit遇到了一些问题。

Requesting authorization works on both the simulator and my device and shows as successful on every launch. 请求授权在模拟器和我的设备上均有效,并且每次启动均显示为成功。 Querying and reading the samples however fails on my device but not on the simulator. 但是,查询和读取样本在我的设备上失败,但在模拟器上失败。

After launching, with successful authorization, when it needs to query or save the workout it says "Authorization is not determined". 启动后,如果获得成功的授权,当它需要查询或保存锻炼时,会显示“未确定授权”。

Both entitlements have set HealthKit to YES, HealthKit and Background capabilities are turned on, NSHealthShareUsageDescription and NSHealthUpdateUsageDescription keys are provided in the iOS Info.plist. 两种授权都将HealthKit设置为YES,HealthKit和Background功能已打开,iOS Info.plist中提供了NSHealthShareUsageDescription和NSHealthUpdateUsageDescription密钥。

Authorization code 授权码

// 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 ?? "")")
        }
    }

Query code (Udemy course) 查询代码(Udemy课程)

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)
}

I put the authorization code in my ExtensionDelegate instead of the same file where I'm querying and it started working. 我将授权代码放在我的ExtensionDelegate中,而不是我正在查询的文件中,它开始起作用。

Still strange that it worked on the simulator but not on an actual device before though. 仍然很奇怪,它虽然可以在模拟器上运行,但之前却不能在实际设备上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NSKeyedArchiver在模拟器上工作,但不在实际设备上 - NSKeyedArchiver working on simulator but not actual device WCSession发送消息在实际设备上不起作用,但在模拟器上起作用 - WCSession send message is not working on the actual device but working on simulator “WatchKit Simulator Actions”无法在实际的Apple Watch设备上运行 - “WatchKit Simulator Actions” not working on actual apple watch device 音频文件可在iOS模拟器中运行,但无法在实际设备上找到 - Audio files working in iOS simulator, but can't be found on actual device NSKeyedArchiver可与模拟器一起使用,但不适用于实际设备 - NSKeyedArchiver works with simulator but not actual device Apple HealthKit 授权不起作用(Xcode 13.3) - 提示授权请求失败 - Apple HealthKit authorization not working (Xcode 13.3) - FAILED prompting authorization request 可达性在模拟器上起作用,但在设备上不起作用 - Reachability working on simulator but not on device prepareForSegue在模拟器上工作但不在设备上工作 - prepareForSegue working on simulator but not on device FileExistAtPath在模拟器上运行,但在设备上不运行 - FileExistAtPath working on Simulator, but not on Device TVOutManager 在模拟器上工作,但不在设备上? - TVOutManager working on Simulator, but not on a device?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM