Skip to content

Commit

Permalink
Merge pull request #251 from beeminder/remove-health-sync-notification
Browse files Browse the repository at this point in the history
Remove health sync notification
  • Loading branch information
andrewpbrett authored Jan 26, 2021
2 parents 5ebd5f5 + 65b74fe commit c53424f
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 100 deletions.
18 changes: 6 additions & 12 deletions BeeSwift/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
resetStateIfUITesting()
removeAllLocalNotifications()

UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.font :
UIFont.beeminder.defaultFontPlain.withSize(20)]
Expand All @@ -36,10 +37,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD

NetworkActivityIndicatorManager.shared.isEnabled = true

if UserDefaults.standard.object(forKey: Constants.healthSyncRemindersPreferenceKey) == nil {
UserDefaults.standard.set(true, forKey: Constants.healthSyncRemindersPreferenceKey)
}

NotificationCenter.default.addObserver(self, selector: #selector(self.updateBadgeCount), name: NSNotification.Name(rawValue: CurrentUserManager.goalsFetchedNotificationName), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.updateBadgeCount), name: NSNotification.Name(rawValue: CurrentUserManager.signedOutNotificationName), object: nil)

Expand Down Expand Up @@ -140,19 +137,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
// MARK: - UNUserNotificationCenterDelegate

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
switch notification.request.identifier {
case JSONGoal.unlockNotificationIdentifier:
// about to present a notification, a reminder to unlock the device
// yet the app is active, thus we can abandon the notification
completionHandler([])
default:
completionHandler([.alert, .sound, .badge])
}
completionHandler([.alert, .sound, .badge])
}

private func resetStateIfUITesting() {
if ProcessInfo.processInfo.arguments.contains("UI-Testing") {
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
}
}

private func removeAllLocalNotifications() {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
}
1 change: 0 additions & 1 deletion BeeSwift/Constants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ struct Constants {
static let nameGoalSortString = "Name"
static let pledgeGoalSortString = "Pledge"
static let deadlineGoalSortString = "Deadline"
static let healthSyncRemindersPreferenceKey = "wantsHealthSyncReminders"
static let healthKitUpdateDictionaryKey = "healthKitUpdateDictionary"
static let goalSortOptions = [Constants.nameGoalSortString, Constants.deadlineGoalSortString, Constants.pledgeGoalSortString, Constants.recentDataGoalSortString]
}
Expand Down
51 changes: 1 addition & 50 deletions BeeSwift/HealthKitConfigViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ class HealthKitConfigViewController: UIViewController {
var tableView = UITableView()
var goals : [JSONGoal] = []
let cellReuseIdentifier = "healthKitConfigTableViewCell"
var syncRemindersSwitch = UISwitch()
let margin = 12

override func viewDidLoad() {
Expand All @@ -30,52 +29,11 @@ class HealthKitConfigViewController: UIViewController {
let backItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = backItem

let syncRemindersContainer = UIView()
self.view.addSubview(syncRemindersContainer)
syncRemindersContainer.backgroundColor = {
if #available(iOS 13.0, *) {
return .secondarySystemBackground
} else {
return .clear
}
}()
syncRemindersContainer.snp.makeConstraints { make in
make.left.equalTo(self.margin)
make.right.equalTo(-self.margin)

make.top.equalTo(self.topLayoutGuide.snp.bottom)
make.height.equalTo(Constants.defaultTextFieldHeight)
}

let syncRemindersLabel = BSLabel()
syncRemindersContainer.addSubview(syncRemindersLabel)
syncRemindersLabel.text = "Sync Health data reminders"
if #available(iOS 13.0, *) {
syncRemindersLabel.backgroundColor = .secondarySystemBackground
} else {
syncRemindersLabel.backgroundColor = .clear
}
syncRemindersLabel.snp.makeConstraints { make in
make.left.equalTo(self.margin)
make.right.equalTo(-self.margin)

make.height.equalTo(Constants.defaultTextFieldHeight)
}

syncRemindersContainer.addSubview(self.syncRemindersSwitch)
self.syncRemindersSwitch.isOn = UserDefaults.standard.bool(forKey: Constants.healthSyncRemindersPreferenceKey)
self.syncRemindersSwitch.addTarget(self, action: #selector(self.syncRemindersSwitchValueChanged), for: .valueChanged)
self.syncRemindersSwitch.snp.makeConstraints { (make) in
make.centerY.equalTo(syncRemindersLabel)
make.right.equalTo(-self.margin)
}

self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { (make) -> Void in
make.left.equalTo(self.margin)
make.right.equalTo(-self.margin)

make.top.equalTo(syncRemindersContainer.snp.bottom).offset(self.margin)
make.top.equalTo(self.topLayoutGuide.snp.bottom).offset(self.margin)
make.bottom.equalTo(self.bottomLayoutGuide.snp.top)
}

Expand Down Expand Up @@ -108,13 +66,6 @@ class HealthKitConfigViewController: UIViewController {
// Dispose of any resources that can be recreated.
}

@objc func syncRemindersSwitchValueChanged() {
UserDefaults.standard.set(self.syncRemindersSwitch.isOn, forKey: Constants.healthSyncRemindersPreferenceKey)
if self.syncRemindersSwitch.isOn == false {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
}

@objc func fetchGoals() {
self.tableView.refreshControl?.endRefreshing()

Expand Down
37 changes: 0 additions & 37 deletions BeeSwift/JSONGoal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,6 @@ class JSONGoal {
guard let sampleType = self.hkSampleType() else { return nil }
return HKObserverQuery(sampleType: sampleType, predicate: nil, updateHandler: { (query, completionHandler, error) in
self.hkQueryForLast(days: 1, success: nil, errorCompletion: nil)
self.setUnlockNotification()
completionHandler()
})
}
Expand Down Expand Up @@ -512,7 +511,6 @@ class JSONGoal {
}
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + .seconds(5), execute: { [weak self] in
self?.updateBeeminderWithStatsCollection(collection: statsCollection, success: nil, errorCompletion: nil)
self?.setUnlockNotification()
})
}

Expand All @@ -526,46 +524,11 @@ class JSONGoal {
}

self?.updateBeeminderWithStatsCollection(collection: statsCollection, success: nil, errorCompletion: nil)
self?.setUnlockNotification()
}
}
healthStore.execute(query)
}

public static let unlockNotificationIdentifier: String = "health sync unlock reminder"

func setUnlockNotification() {
guard UserDefaults.standard.bool(forKey: Constants.healthSyncRemindersPreferenceKey) else { return }

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
content.title = "Health Sync"
content.body = "Unlock your phone to sync your Health data with Beeminder."
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)

var trigger : UNNotificationTrigger
if hour < 9 {
// data synced before 9 am. Schedule for nine hours from now.
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 32400.0, repeats: false)
}
else if hour >= 9 && hour < 17 {
// data synced during the day, before 5 pm. schedule for 8 pm.
var components = DateComponents()
components.hour = 20
trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
} else {
// data synced after 5 pm. Schedule for 9 am next morning.
var components = DateComponents()
components.hour = 9
trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
}

let notification = UNNotificationRequest.init(identifier: JSONGoal.unlockNotificationIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(notification, withCompletionHandler: nil)
}

func updateBeeminderWithStatsCollection(collection : HKStatisticsCollection, success: (() -> ())?, errorCompletion: (() -> ())?) {
guard let healthStore = HealthStoreManager.sharedManager.healthStore else { return }

Expand Down

0 comments on commit c53424f

Please sign in to comment.