when try read data in healthkit error telling me application crashed because of
fatal error: unexpectedly found nil while unwrapping optional value
i understand trying unwrap optional nil
, when try use optionals error telling me force unwrap it.
here of code using:
import foundation import healthkit import uikit class healthmanager { let healthkitstore = hkhealthstore() func authorizehealthkit(completion: ((success: bool, error: nserror) -> void)!) { // set data read healthkit store let healthkittypestoread: set<hkobjecttype> = [(hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifieractiveenergyburned))!, hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifierflightsclimbed)!, hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifiernikefuel)!, hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifierstepcount)!, hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifierdistancewalkingrunning)!] // check if healthkit available if !hkhealthstore.ishealthdataavailable() { let error = nserror(domain: "com.mycompany.appname", code: 2, userinfo: [nslocalizeddescriptionkey: "healthkit not available on 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 try remove bang operator(!) error saying that:
value of optional type 'hkquantitytype?' not unwrapped; did mean use '!'?
since quantitytypeforidentifier
returns hkquantitytype?
, force unwrapping can result in unwrapping nil value, know. have check nil, example in form:
if let objecttype = hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifierflightsclimbed) { // add objecttype set }
Comments
Post a Comment