참고
HealthKit_SleepData
import HealthKit
let healthStore = HKHealthStore()
var startedSleepData : Bool = true
var sleepTime = String()
var calc : Double = 0.0
class InterfaceController: WKInterfaceController {
func authorizeHealthKit() {
// 수면시간 권한 요청
let typeToRead = Set([HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!])
let typeToShare = Set([HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!])
healthStore.requestAuthorization(toShare: typeToShare, read: typeToRead) { (success, error) in
if error != nil {
print(error.debugDescription)
} else {
if success {
print("권한이 허락되었습니다.")
self.getSleepData()
} else {
print("권한이 아직 없습니다.")
}
}
}
}
@IBAction func sBtnTapped() {
print("sleepDataManager")
totalSleepLabel.setText("\(sleepTime)")
sleepDataCalc()
}
func sleepDataManager() {
if !startedSleepData { // false
print("sleepDataManager error")
} else {
print("sleepDataManager success")
totalSleepLabel.setText("\(sleepTime)")
sleepDataCalc()
}
}
func sleepDataCalc() {
print("sleepDataCalc : \(sleepTime)")
if calc <= 18000 { // 5시간
self.sleepDataLabel.setText("졸음 운전 주의하세요.")
} else {
self.sleepDataLabel.setText("안전 운전하세요.")
}
}
// 수면 데이터 가져오기
// https://eysermans.com/post/creating-an-ios-14-widget-showing-health-data
func getSleepData() {
guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else {
return
}
let startDate = Calendar.current.date(byAdding: .day, value: -1, to: Date())
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictEndDate)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: 30, sortDescriptors: [sortDescriptor]) {
(query, result, error) in
guard error == nil else {
print("Something went wrong getting sleep analysis")
self.startedSleepData = !self.startedSleepData
return
}
print("success")
var totalSeconds : Double = 0.0
if let result = result {
for item in result {
if let sample = item as? HKCategorySample {
let timeInterval = sample.endDate.timeIntervalSince(sample.startDate)
totalSeconds = totalSeconds + timeInterval
print("SleepData StartDate \(sample.startDate) : SleepData EndDate: \(sample.endDate)")
}
}
}
let result =
String(Int(totalSeconds / 3600)) + "h " +
String(Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)) + "m " +
String(Int(totalSeconds.truncatingRemainder(dividingBy: 3600).truncatingRemainder(dividingBy: 60))) + "s"
print("totalSleepTime : \(result)")
self.sleepTime = result
self.calc = totalSeconds
self.sleepDataManager()
}
healthStore.execute(query)
}
Swift
복사