我可以在 iOS 后台提取中进行网络调用吗?



我目前正在尝试在用户有新消息时创建通知。我正在尝试使用本地通知来执行此操作,因为我是一个非常初学者,而且它似乎(?(比推送通知更容易。我的问题是,我可以在后台提取期间检查我的 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)
}
}
}

最好考虑使用推送通知,因为这样您的用户就不必等到 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)
}
}

最新更新