Harish
Harish

Reputation: 1408

HealthKit (Unexpectedly found nil when unwrapping an optional)

When I try to read data in HealthKit I get an error telling me that the application crashed because of

fatal error: unexpectedly found nil while unwrapping an Optional value

I understand that I am trying to unwrap an optional that is nil, but when I try to use optionals I get an error telling me to force unwrap it.

Here is some of the code that I am using:

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

Also, if I try to remove the bang operator(!) I get an error saying that:

Value of optional type 'HKQuantityType?' not unwrapped; did you mean to use '!'?

Upvotes: 0

Views: 191

Answers (2)

Harish
Harish

Reputation: 1408

I realized that when I was requesting HealthKit access this piece of code was returning nil:

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

It turns out that the error was actually nil and I was force unwrapping the nil. As a result, I changed the code to:

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

Upvotes: 0

Dominic K
Dominic K

Reputation: 7075

Since quantityTypeForIdentifier returns HKQuantityType?, then force unwrapping it can result in unwrapping a nil value, as you know. You have to check for nil, for example in the form:

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

Upvotes: 1

Related Questions