我正在尝试制作推送通知,当app使用计时器移动到后台(用户按主页按钮)时,该通知会正常工作。这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound,.badge],
completionHandler: nil);
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)
}
var timer: Timer = Timer()
func appMovedToBackground() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(observeUnreadedMsgs), userInfo: nil, repeats: true)
}
func observeUnreadedMsgs() {
let ref = FIRDatabase.database().reference().child("chats")
//... some code which gets new message in chat
self.sendNotification(userName: userName, msgText: msg)
// ...
}
func sendNotification(userName: String, msgText: String) {
let content = UNMutableNotificationContent()
content.title = userName
content.subtitle = ""
content.body = msgText
//Set the trigger of the notification -- here a timer.
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 5.0,
repeats: false)
//Set the request for the notification from the above
let request = UNNotificationRequest(
identifier: msgText,
content: content,
trigger: trigger
)
//Add the notification to the currnet notification center
UNUserNotificationCenter.current().add(
request, withCompletionHandler: nil)
}
但是此代码只返回1个推送通知,并且不再执行。我在哪里错了?