Last active
November 27, 2019 13:08
-
-
Save KaneCheshire/0d109b03a987ced4260af8dcc6fa55e8 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 UIKit | |
import HealthKit | |
@UIApplicationMain | |
class AppDelegate: UIResponder, UIApplicationDelegate { | |
var window: UIWindow? | |
private let store = HKHealthStore() | |
private let falls = HKObjectType.quantityType(forIdentifier: .numberOfTimesFallen)! | |
private var lastAnchor: HKQueryAnchor? | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { | |
requestPermissionToDetectFalls() | |
return true | |
} | |
private func requestPermissionToDetectFalls() { | |
store.requestAuthorization(toShare: nil, read: [falls]) { success, error in | |
print("Finished requesting authorization", success, error) | |
self.observeFalls() | |
} | |
} | |
private func observeFalls() { | |
let query = HKObserverQuery(sampleType: falls, predicate: nil) { query, handler, error in | |
self.checkNewFalls() | |
handler() | |
} | |
store.execute(query) | |
} | |
private func checkNewFalls() { | |
let query = HKAnchoredObjectQuery(type: falls, predicate: nil, anchor: lastAnchor, limit: HKObjectQueryNoLimit) { query, sample, deleted, anchor, error in | |
defer { self.lastAnchor = anchor } | |
guard self.lastAnchor != nil else { return } | |
guard sample?.isEmpty == false else { return } | |
self.presentFallAlert() | |
} | |
store.execute(query) | |
} | |
private func presentFallAlert() { | |
DispatchQueue.main.async { | |
let alert = UIAlertController(title: "You fell!", message: "Are you okay?", preferredStyle: .alert) | |
alert.addAction(.init(title: "Yes, thanks!", style: .default)) | |
alert.addAction(.init(title: "No!", style: .default)) | |
self.window?.rootViewController?.present(alert, animated: true) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment