Created
January 24, 2021 15:48
-
-
Save choplin/cbdf9bf43d6f109ece468b80c5b95a6b to your computer and use it in GitHub Desktop.
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
import SwiftUI | |
import HealthKit | |
struct ContentView: View { | |
@State var labelText = "Get Data" | |
@State var flag = false | |
let healthStore = HKHealthStore() | |
let allTypes = Set([ | |
HKSeriesType.heartbeat(), | |
HKObjectType.quantityType(forIdentifier: .heartRate)!, | |
HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!, | |
]) | |
var body: some View { | |
VStack() { | |
Text(labelText) | |
.font(.largeTitle) | |
.padding(.bottom) | |
Button(action: { | |
if(self.flag) { | |
self.labelText = "Get Data" | |
self.flag = false | |
} else { | |
if HKHealthStore.isHealthDataAvailable() { | |
self.labelText = "Succeeded!" | |
self.healthStore.requestAuthorization(toShare: nil, read: self.allTypes) { (success, error) in | |
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) | |
let query = HKSampleQuery(sampleType: HKSeriesType.heartbeat(), | |
predicate: nil, | |
limit: HKObjectQueryNoLimit, | |
sortDescriptors: [sortDescriptor]) { (_, samples, _) in | |
if let sample = samples?.first as? HKHeartbeatSeriesSample { | |
print("series start:\(sample.startDate)\tend:\(sample.endDate)") | |
let seriesQuery = HKHeartbeatSeriesQuery(heartbeatSeries: sample) { | |
query, timeSinceSeriesStart, precededByGap, done, error in | |
let formatted = String(format: "%.2f", timeSinceSeriesStart) | |
print("timeSinceSeriesStart:\(formatted)\tprecededByGap:\(precededByGap)\t done:\(done)") | |
} | |
self.healthStore.execute(seriesQuery) | |
} | |
} | |
self.healthStore.execute(query) | |
} | |
} else { | |
self.labelText = "Unavailabe" | |
} | |
self.flag = true | |
} | |
}) { | |
Text("Button") | |
.font(.largeTitle) | |
.foregroundColor(Color.white) | |
} | |
.padding(.all) | |
.background(Color.blue) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment