I am making an attempt to ship customers a notification once they attain a sure step depend.
I am utilizing the well being package enableBackgroundDelivery technique to set this up and making an attempt to get a quantity from userDefaults to find out what the goal step depend ought to be and evaluating to the present quantity from the well being retailer.
For some purpose, this is not working and I don’t know the right way to debug it. I’ve managed to get it working with out fetching the worth from consumer defaults and simply hard-coding one thing.
I am triggering this operate under from a swift ui view onAppear when the consumer opens the app. When it runs, I see it will get the precise worth printed from consumer defaults, each my stepInterval
and depend
are Int. I am unable to see how the stepInterval
variable would not be accessible when it runs once more within the background however that its okay operating with a hardcoded worth, I am fairly certain my permissions are high-quality. What’s the scope of the background supply completion? What may I be doing unsuitable?
func setupBackgroundTracking() {
let quantityType = HKObjectType.quantityType(forIdentifier: .stepCount)!
print("amount")
guard let lastRedemption = Config.userLastRedemptionTime,
let stepInterval = Config.userLevelStepInterval else {
print("could not learn config")
return
}
print("config: (lastRedemption), (stepInterval)")
healthStore.enableBackgroundDelivery(for: quantityType, frequency: .hourly) { (success, error) in
if !success {
if let error = error {
print("didn't get steps (error.localizedDescription)")
}
print("didn't get steps - no error")
return
}
print("config interior: (lastRedemption), (stepInterval)")
fetchStepsSince(lastRedemptionTime: lastRedemption, now: Date()) { depend in
print("step depend was (depend)")
if depend >= stepInterval {
print("beginning to schedule notification")
scheduleNotification(lastRedemption: lastRedemption)
}
}
}
}
My Config consumer defaults entry is outlined as follows
class Config {
static var userLevelStepInterval: Int? {
get {
return self.userDefaults.object(forKey: "userLevelStepInterval") as? Int
}
set {
self.userDefaults.set(newValue, forKey: "userLevelStepInterval")
}
}
...
And my scheduleNotification
operate is as follows:
func scheduleNotification(lastRedemption: Date) {
let content material = UNMutableNotificationContent()
let (title, physique) = getRandomUserMessage()
content material.title = title
content material.physique = physique
content material.sound = UNNotificationSound.default
print("scheduling Notification")
let set off = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content material: content material, set off: set off)
UNUserNotificationCenter.present().add(request) { (error) in
if let error = error {
print("couldn't ship notification (error.localizedDescription)")
return
}
print("added notidication ")
}
}