Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- 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)")
- })
- }
- })
- }
- }
Add Comment
Please, Sign In to add comment