【发布时间】:2018-10-22 14:05:16
【问题描述】:
我需要让我的应用获取数据并根据响应向用户显示警报,我正在尝试创建一个函数,然后在 appDelegate 类上调用它...
功能:
func triggerPushMessages(){
Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { (time) in
// I want to perform a request here to show the alert to user
let content = UNMutableNotificationContent()
content.title = "testNotifications on background state"
content.body = "date of notification: \(Date().timeIntervalSinceNow)"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let notificationRequest = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(notificationRequest, withCompletionHandler: { (err) in
if let error = err {print(error);return}
})
}
}
我创建了这个函数来测试我设置定时器后通知是否会显示,但是当我设置 timer.schedule 函数时,pushNotification 不起作用,如果我删除定时器 pushNotification 工作......
问题是,我需要先从 Api 请求数据,等待响应,然后显示推送通知以提醒用户...
我该怎么做?
我调用这个方法:
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
self.triggerPushMessages()
}
有可能吗? whatsapp、电报、火种等应用如何处理/获取后台状态数据,然后向用户显示通知?
提前感谢您的回答。
我想补充一点,我的 60 秒请求仅用于测试目的,我将每小时执行一次请求...
【问题讨论】:
标签: swift xcode timer apple-push-notifications appdelegate