我可以在iOS后台获取内进行网络通话吗?

时间:2018-08-20 07:54:15

标签: ios swift firebase notifications uilocalnotification

我当前正在尝试在用户收到新消息时创建通知。我正在尝试使用本地通知进行此操作,因为我是一个初学者,它似乎比推送通知更容易?我的问题是,我可以在后台获取过程中检查Firebase数据库吗?

我所经历的是后台获取功能有效-但仅在我的应用程序内存被挂起之前,从而否定了后台获取的要点。我运行它,模拟了背景提取,但是除非应用程序刚刚打开,否则它什么都不做,并告诉我“ Warning: Application delegate received call to -application:performFetchWithCompletionHandler: but the completion handler was never called.

如果有用,这是我的代码。我知道这似乎是一种时髦的方式。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        //Firebase
        FirebaseApp.configure()

        //there was other firebase stuff here that I don't think is relevant to this question

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in

        }

        UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)

        return true
    }

    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        myDatabase.child("users").child(userID!).child("hasNewMessages").observeSingleEvent(of: .value) { (snapshot) in
            if snapshot.value as! Bool == true {
                let content = UNMutableNotificationContent()
                content.title = "You have unread messages"
                content.badge = 1

                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
                let request = UNNotificationRequest(identifier: "testing", content: content, trigger: trigger)

                UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

最好使用推送通知,这样您的用户不必等到iOS决定调用您的后台抓取操作;他们可以立即收到新消息的通知。

但是,您的问题与控制台中显示的消息相同;您需要在完成后台操作后调用传递给后台获取方法的completionHandler,以使iOS知道发生了什么。它使用这些信息来调整调用后台获取方法的频率和时间。

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    myDatabase.child("users").child(userID!).child("hasNewMessages").observeSingleEvent(of: .value) { (snapshot) in
        if snapshot.value as! Bool == true {
            let content = UNMutableNotificationContent()
            content.title = "You have unread messages"
            content.badge = 1

            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
            let request = UNNotificationRequest(identifier: "testing", content: content, trigger: trigger)

            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }
        completionHandler(.newData)
    }
}