我正在使用Firebase消息(通知)向iOS上的用户发送推送提醒。对于我的应用程序,这是一个待办事项应用程序,我使用的是Swift 3。当用户收到推送通知时,我希望他们能够直接从推送通知中完成任务。
一切都很好。用户获得推送。当他们3d触摸时,他们会看到“完成按钮”。当点击“完成按钮”时,应用程序中的didReceive响应方法会在后台触发。
在这种方法中,我使用一个闭包,然后在该闭包中使用一个闭包。出于某种原因,代码的第一部分在后台运行,用户不打开应用程序,但最后一部分仅在用户再次打开应用程序时运行(见下文)。为什么?
这是我的代码:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if response.actionIdentifier == notificationActionComplete, let actionKey = userInfo["actionKey"] as? String {
getAction(actionKey: actionKey, completion: { (action) in
action.complete {
}
})
}
completionHandler()
}
func getAction(actionKey: String, completion:@escaping (Action)->Void) {
Database.database().reference(withPath: "actions/\(actionKey)").observeSingleEvent(of: .value, with: { snapshot in
let action = Action(snapshot: snapshot)
completion(action)
})
}
实际课堂:
var ref: DatabaseReference?
init(snapshot: DataSnapshot) {
key = snapshot.key
ref = snapshot.ref
//Other inits here
}
func complete(completion:@escaping (Void) -> Void) {
//This code to remove the node is running fine in background
ref.removeValue { (error, ref) in
//The code in here is not running until the user opens the app next time
otherRef.updateChildValues(self.toAnyObject(), withCompletionBlock: { (error, ref) in
completion()
})
}