Skip to content

Instantly share code, notes, and snippets.

@eyepaq
Created February 25, 2018 03:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyepaq/a750c017229ded75a19a49a26bc087f1 to your computer and use it in GitHub Desktop.
Save eyepaq/a750c017229ded75a19a49a26bc087f1 to your computer and use it in GitHub Desktop.
Quick and dirty import of CSV data into HealthKit .bodyMass measurements. I used this to import my Withings health data export.
/**
Quick and dirty CSV importer, only used once by me to import my own data, sharing it here
in case anyone finds it useful.
*/
class HealthKitCSVImporter {
let healthStore = HKHealthStore()
let bodyMassType = HKSampleType.quantityType(forIdentifier: .bodyMass)!
func authorizeHealthKit(completion: @escaping ((_ success: Bool, _ error: Error?) -> Void)) {
if !HKHealthStore.isHealthDataAvailable() {
return
}
let readDataTypes: Set<HKSampleType> = [bodyMassType]
healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) in
completion(success, error)
}
}
func importData() {
healthStore.requestAuthorization(toShare: [bodyMassType], read: [bodyMassType], completion: { (success, error) in
if success {
// Load "weight.csv" from the app bundle
guard let path = Bundle.main.path(forResource: "weight", ofType: "csv") else {
return
}
// Convert CSV data into UTF-8 string, split it at newlines
let csvData = try! Data.init(contentsOf: URL(fileURLWithPath: path))
let csvString = String(data: csvData, encoding: .utf8)!
let lines = csvString.split(separator: "\n")
var lineNum = 0
// Walk each line after the first, turning each row into a .bodyMass sample
var records = [HKObject]()
lines.forEach { line in
lineNum = lineNum + 1
if (lineNum > 1) {
// Split into comma-separated fields
let fields = line.split(separator:",")
// Fields are quoted, so remove the quotes
let dateStr = fields[0].replacingOccurrences(of: "\"", with: "")
let weightStr = fields[1].replacingOccurrences(of: "\"", with: "")
// Dates in my file are formatted "2016-03-23 17:40:23", set up a DateFormatter to parse
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from:String(dateStr))!
// Weight is in pounds
let weight = Double(weightStr)!
NSLog("Date: \(date), weight: \(weight)")
let bodyMassSample = HKQuantitySample(type: self.bodyMassType,
quantity: HKQuantity(unit: HKUnit.pound(), doubleValue: weight),
start: date,
end: date)
records.append(bodyMassSample)
}
}
// Save all the records to HealthKit
self.healthStore.save(records, withCompletion: { (succ, err) in
NSLog("All done, error=\(err)")
})
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment