【问题标题】:HealthKit (Unexpectedly found nil when unwrapping an optional)HealthKit(打开可选时意外发现 nil)
【发布时间】:2016-01-24 22:48:52
【问题描述】:

当我尝试在 HealthKit 中读取数据时,我收到一条错误消息,告诉我应用程序因

而崩溃

致命错误:在展开可选值时意外发现 nil

我知道我正在尝试解包 nil 的可选项,但是当我尝试使用可选项时,我收到一个错误,告诉我强制解包。

这是我正在使用的一些代码:

import Foundation
import HealthKit
import UIKit

class HealthManager {
let healthKitStore = HKHealthStore()

func authorizeHealthKit(completion: ((success: Bool, error: NSError) -> Void)!) {
    // Set the Data to be read from the HealthKit Store
    let healthKitTypesToRead: Set<HKObjectType> = [(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned))!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierFlightsClimbed)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierNikeFuel)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!]

    // Check if HealthKit is available
    if !HKHealthStore.isHealthDataAvailable() {
        let error = NSError(domain: "com.MyCompany.appName", code: 2, userInfo: [NSLocalizedDescriptionKey: "HealthKit is not available on this device"])
        if completion != nil {
            completion?(success: false, error: error)
        }
        return;
    }

    // Request HealthKit Access
    self.healthKitStore.requestAuthorizationToShareTypes(nil, readTypes: healthKitTypesToRead) {
        (success, error) -> Void in
        if completion != nil {
            completion?(success: true, error: error!)
        }
    }
}
}

此外,如果我尝试删除 bang 运算符(!),我会收到一条错误消息:

可选类型“HKQuantityType?”的值未拆封;您的意思是使用“!”吗?

【问题讨论】:

  • HKObjectType.quantityTypeForIdentifier(...) 返回一个可选的HKQuantityType。您应该验证这些调用都没有返回nil
  • @JAL 好的,我想我知道是什么导致了 nil。

标签: swift optional healthkit


【解决方案1】:

既然quantityTypeForIdentifier 返回HKQuantityType?,那么强制解包可能会导致解包零值,如您所知。您必须检查 nil,例如:

if let objectType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierFlightsClimbed) {
    // Add objectType to set
}

【讨论】:

    【解决方案2】:

    我意识到当我请求访问 HealthKit 时,这段代码返回了nil

            if completion != nil {
            completion?(success: true, error: error!)
        }
    

    事实证明,error 实际上是 nil,而我是强制解开 nil 的。结果我把代码改成了:

                if error != nil && completion != nil {
                completion?(success: true, error: error!)
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多