代码之家  ›  专栏  ›  技术社区  ›  Martin

从远程通知获取要在后台运行的方法

  •  2
  • Martin  · 技术社区  · 9 年前

    我正在使用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()        
        })
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Jeremy Brown    8 年前

    在调用userNotificationCenter()的runloop循环之后,你的应用程序基本上处于暂停状态,因此如果你的完成处理程序响应异步工作,那么在你的应用程序再次恢复之前,该工作永远不会发生。为了解决这个问题,您可能需要在该函数内开始一个后台任务,然后让您的完成处理程序在后台任务完成后结束它。这会告诉系统您需要在后台保持一段时间的活动状态(但如果您花费的时间太长,则无法保证)

    https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

    推荐文章