Last active
October 30, 2016 16:32
-
-
Save hiddevdploeg/eb3918d757ca17404022d300291c59f8 to your computer and use it in GitHub Desktop.
Why is the LatestMeasure function returning empty values?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Weight.swift | |
// Vekt | |
// | |
// Created by Hidde van der Ploeg on 26/09/2016. | |
// Copyright © 2016 Hidde van der Ploeg. All rights reserved. | |
// | |
import UIKit | |
import HealthKit | |
private let getWeight = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) | |
let healthKitStore:HKHealthStore = HKHealthStore() | |
let healthKitManager: HealthKitManager = HealthKitManager() | |
let weightQuery = HKSampleQuery( sampleType: getWeight!, predicate: nil, limit: 999, sortDescriptors: nil, resultsHandler: { (sampleQuery, results, error ) -> Void in | |
if let queryError = error { | |
return | |
}} ) | |
struct Weight { | |
var weight : String | |
var unit : String | |
var date : String? | |
init(_ weight: String, unit: String, date: String?){ | |
self.weight = weight | |
self.unit = unit | |
self.date = date | |
} | |
} | |
var current = Weight("", unit: "", date: "") | |
func isStorePossible() { | |
healthKitManager.setupHealthStoreIfPossible { (success, error) -> Void in | |
if error == nil { | |
// health kit was setup successfully | |
} else { | |
print("Error occured while setting up Health Kit: \(error!.localizedDescription)") | |
} | |
} | |
} | |
func latestMeasure() -> Weight? { | |
var latestWeight: Weight? | |
isStorePossible() | |
healthKitManager.readMostRecentSample(getWeight!, completion: { (mostRecentWeight, error) -> Void in | |
if (error != nil) { | |
print("Error reading weight from HealthKit Store: \(error?.localizedDescription)") | |
return; | |
} | |
var weightLocalizedString = "" | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd" | |
dateFormatter.dateStyle = .medium | |
dateFormatter.timeStyle = .short | |
let date = dateFormatter.string(from: (mostRecentWeight?.endDate)!) | |
let weight = mostRecentWeight as? HKQuantitySample; | |
if let kilograms = weight?.quantity.doubleValue(for: HKUnit.gramUnit(with: .kilo)) { | |
let weightFormatter = MassFormatter() | |
weightFormatter.isForPersonMassUse = true; | |
weightLocalizedString = weightFormatter.string(fromKilograms: kilograms) | |
} | |
let fullAmount = weightLocalizedString.characters.split{$0 == " "}.map(String.init) | |
let amount = fullAmount[0] | |
let unit = fullAmount[1] | |
latestWeight = Weight(amount, unit: unit, date: date) | |
}) | |
return latestWeight | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment