-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRNSwiftHealthkit.swift
298 lines (226 loc) · 8.1 KB
/
RNSwiftHealthkit.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//
// RNSwiftHealthkit.swift
// <your-project-name>
//
// Created by Chris McLellan on 29/06/16.
// Healthkit code from https://www.raywenderlich.com/86336/ios-8-healthkit-swift-getting-started
//
import Foundation
import HealthKit
@objc(RNSwiftHealthKit)
class RNSwiftHealthKit: NSObject {
var bridge: RCTBridge! // this is synthesized
let healthKitStore:HKHealthStore = HKHealthStore() // an instance of the healthkit store
@objc func typesSetFromDictionary (types: NSDictionary) -> Set <HKObjectType> {
var typesSet = Set<HKObjectType>()
if (types["characteristic"] != nil) {
let typeCharacteristics = types["characteristic"] as! NSArray;
for characteristic in typeCharacteristics {
let characteristicIdentifier = HKObjectType.characteristicTypeForIdentifier(characteristic as! String);
typesSet.insert(characteristicIdentifier!);
}
}
if (types["quantity"] != nil) {
let typeQuantities = types["quantity"] as! NSArray;
for quantity in typeQuantities {
let quantityIdentifier = HKObjectType.quantityTypeForIdentifier(quantity as! String);
typesSet.insert(quantityIdentifier!);
}
}
if (types["category"] != nil) {
let typeCategories = types["category"] as! NSArray;
for category in typeCategories {
let categoryIdentifier = HKObjectType.categoryTypeForIdentifier(category as! String);
typesSet.insert(categoryIdentifier!);
}
}
if (types["workout"] != nil) {
let workoutIdentifier = HKObjectType.workoutType();
typesSet.insert(workoutIdentifier);
}
return typesSet;
}
@objc func authorizeHealthKit (typesToWrite: NSDictionary, typesToRead: NSDictionary) -> Void {
// 1. Set the types you want to write to HK Store using typesSetFromDictionary
let typesToWriteSet:Set = typesSetFromDictionary(typesToWrite);
// 2. Set the types you want to read from HK Store using typesSetFromDictionary
let typesToReadSet:Set = typesSetFromDictionary(typesToRead);
// 3. If the store is not available (for instance, iPad) return
if !HKHealthStore.isHealthDataAvailable()
{
return;
}
// 4. Request HealthKit authorization
healthKitStore.requestAuthorizationToShareTypes(typesToWriteSet as? Set<HKSampleType>, readTypes: typesToReadSet) { (success, error) -> Void in}
}
func readBirthDate (callback: (NSObject) -> ()) -> Void
{
var error:NSError?
var age:Int!
// Read age and DOB
do {
let birthDay = try healthKitStore.dateOfBirth()
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let differenceComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: birthDay, toDate: today, options: NSCalendarOptions(rawValue: 0))
age = differenceComponents.year
} catch let error as NSError {
print(error.localizedDescription)
}
let ret = [
"age": age,
]
callback([ret])
}
func readBiologicalSex (callback: (NSObject) -> ()) -> Void
{
var error:NSError?
var biologicalSex: HKBiologicalSexObject?
// Read biological sex - (will be added to return statement once enum problem solved)
do {
biologicalSex = try healthKitStore.biologicalSex();
} catch let error as NSError {
print(error.localizedDescription)
}
var biologicalSexDefined = biologicalSexLiteral(biologicalSex?.biologicalSex);
let ret = [
"sex": biologicalSexDefined
]
callback([ret])
}
func readBloodType(callback: (NSObject) -> ()) -> Void
{
var error:NSError?
var bloodType: HKBloodTypeObject?
// Read blood type - (will be added to return statement once enum problem solved)
do {
bloodType = try healthKitStore.bloodType()
print(bloodType);
} catch let error as NSError {
print(error.localizedDescription)
}
var bloodTypeDefined = bloodTypeLiteral(bloodType?.bloodType);
let ret = [
"bloodType": bloodTypeDefined
]
callback([ret])
}
func biologicalSexLiteral(biologicalSex:HKBiologicalSex?)->String
{
var biologicalSexText = "Unknown";
if biologicalSex != nil {
switch( biologicalSex! )
{
case .Female:
biologicalSexText = "Female"
case .Male:
biologicalSexText = "Male"
default:
break;
}
}
return biologicalSexText;
}
func bloodTypeLiteral(bloodType:HKBloodType?)->String
{
var bloodTypeText = "Unknown";
if bloodType != nil {
switch( bloodType! ) {
case .APositive:
bloodTypeText = "A+"
case .ANegative:
bloodTypeText = "A-"
case .BPositive:
bloodTypeText = "B+"
case .BNegative:
bloodTypeText = "B-"
case .ABPositive:
bloodTypeText = "AB+"
case .ABNegative:
bloodTypeText = "AB-"
case .OPositive:
bloodTypeText = "O+"
case .ONegative:
bloodTypeText = "O-"
default:
break;
}
}
return bloodTypeText;
}
func readMostRecentSample(sampleType:HKSampleType , completion: ((HKSample!, NSError!) -> Void)!)
{
// 1. Build the Predicate
let past = NSDate.distantPast() as! NSDate
let now = NSDate()
let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)
// 2. Build the sort descriptor to return the samples in descending order
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
// 3. we want to limit the number of samples returned by the query to just 1 (the most recent)
let limit = 1
// 4. Build samples query
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor])
{ (sampleQuery, results, error ) -> Void in
if let queryError = error {
completion(nil,error)
return;
}
// Get the first sample
let mostRecentSample = results!.first as? HKQuantitySample
// Execute the completion closure
if completion != nil {
completion(mostRecentSample,nil)
}
}
// 5. Execute the Query
self.healthKitStore.executeQuery(sampleQuery)
}
func readWeight(callback: (NSObject) -> ()) -> Void
{
// 1. Construct an HKSampleType for weight
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
// 2. Call the method to read the most recent weight sample
readMostRecentSample(sampleType!, completion: { (mostRecentWeight, error) -> Void in
if( error != nil )
{
print("Error reading weight from HealthKit Store: \(error.localizedDescription)")
return;
}
var weightLocalizedString = "Unknown";
let weight = mostRecentWeight as? HKQuantitySample;
if let kilograms = weight?.quantity.doubleValueForUnit(HKUnit.gramUnitWithMetricPrefix(.Kilo)) {
let weightFormatter = NSMassFormatter()
weightFormatter.forPersonMassUse = true;
weightLocalizedString = weightFormatter.stringFromKilograms(kilograms)
}
let ret = [
"weight": weightLocalizedString
]
callback([ret])
});
}
func readHeight(callback: (NSObject) -> ()) -> Void
{
// 1. Construct an HKSampleType for weight
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
// 2. Call the method to read the most recent weight sample
readMostRecentSample(sampleType!, completion: { (mostRecentHeight, error) -> Void in
if( error != nil )
{
print("Error reading height from HealthKit Store: \(error.localizedDescription)")
return;
}
var heightLocalizedString = "Unknown";
let height = mostRecentHeight as? HKQuantitySample;
if let meters = height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) {
let heightFormatter = NSLengthFormatter()
heightFormatter.forPersonHeightUse = true;
heightLocalizedString = heightFormatter.stringFromMeters(meters);
}
let ret = [
"height": heightLocalizedString
]
callback([ret])
});
}
}