HealthKit(打开可选项时意外发现nil)

时间:2016-01-24 22:48:53

标签: swift optional health-kit

当我尝试在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?'的值没有打开;你的意思是用'!'吗?

2 个答案:

答案 0 :(得分:1)

由于quantityTypeForIdentifier返回HKQuantityType?,因此强制展开它会导致解包nil值,如您所知。您必须检查nil,例如以下列形式:

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

答案 1 :(得分:0)

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

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

事实证明,error实际上是零,我强行解开零。结果,我将代码更改为:

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