Guest User

Untitled

a guest
Mar 6th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.26 KB | None | 0 0
  1. /**
  2. Quick and dirty CSV importer, only used once by me to import my own data, sharing it here
  3. in case anyone finds it useful.
  4. */
  5. class HealthKitCSVImporter {
  6.  
  7. let healthStore = HKHealthStore()
  8. let bodyMassType = HKSampleType.quantityType(forIdentifier: .bodyMass)!
  9.  
  10. func authorizeHealthKit(completion: @escaping ((_ success: Bool, _ error: Error?) -> Void)) {
  11.  
  12. if !HKHealthStore.isHealthDataAvailable() {
  13. return
  14. }
  15.  
  16. let readDataTypes: Set<HKSampleType> = [bodyMassType]
  17.  
  18. healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) in
  19. completion(success, error)
  20. }
  21. }
  22.  
  23.  
  24. func importData() {
  25. healthStore.requestAuthorization(toShare: [bodyMassType], read: [bodyMassType], completion: { (success, error) in
  26. if success {
  27. // Load "weight.csv" from the app bundle
  28. guard let path = Bundle.main.path(forResource: "weight", ofType: "csv") else {
  29. return
  30. }
  31.  
  32. // Convert CSV data into UTF-8 string, split it at newlines
  33. let csvData = try! Data.init(contentsOf: URL(fileURLWithPath: path))
  34. let csvString = String(data: csvData, encoding: .utf8)!
  35. let lines = csvString.split(separator: "\n")
  36. var lineNum = 0
  37.  
  38. // Walk each line after the first, turning each row into a .bodyMass sample
  39. var records = [HKObject]()
  40. lines.forEach { line in
  41. lineNum = lineNum + 1
  42. if (lineNum > 1) {
  43. // Split into comma-separated fields
  44. let fields = line.split(separator:",")
  45.  
  46. // Fields are quoted, so remove the quotes
  47. let dateStr = fields[0].replacingOccurrences(of: "\"", with: "")
  48. let weightStr = fields[1].replacingOccurrences(of: "\"", with: "")
  49.  
  50. // Dates in my file are formatted "2016-03-23 17:40:23", set up a DateFormatter to parse
  51. let dateFormatter = DateFormatter()
  52. dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
  53. let date = dateFormatter.date(from:String(dateStr))!
  54.  
  55. // Weight is in pounds
  56. let weight = Double(weightStr)!
  57.  
  58. NSLog("Date: \(date), weight: \(weight)")
  59.  
  60. let bodyMassSample = HKQuantitySample(type: self.bodyMassType,
  61. quantity: HKQuantity(unit: HKUnit.pound(), doubleValue: weight),
  62. start: date,
  63. end: date)
  64. records.append(bodyMassSample)
  65. }
  66. }
  67.  
  68. // Save all the records to HealthKit
  69. self.healthStore.save(records, withCompletion: { (succ, err) in
  70. NSLog("All done, error=\(err)")
  71. })
  72. }
  73. })
  74. }
  75. }
Add Comment
Please, Sign In to add comment