Ios 在swift 4中显示Firebase通知弹出窗口
注意:解决方案在底部。 原版。 我按照firebase上的说明在iOS中设置推送通知。我确实成功地获得了手机通知,如果应用程序关闭,我会在手机顶部显示通知,但如果我在应用程序中,则不会显示通知。我在终端上看到了打印件,所以我知道它收到了通知 理想的功能是: 1) 如果当用户单击通知时,应用程序已关闭或处于后台,则会打开应用程序,然后会显示应用程序内弹出警报,通知中会显示“确定”按钮以单击 2) 如果应用程序位于前台,通知将显示为弹出警报,并单击“确定”按钮 下面是AppDelegate.swift代码,当我运行它并发送通知时,我会收到通知,但在尝试显示警报时也会出现以下错误警告:尝试在视图不在窗口层次结构中的Company.AuthorizationCheckViewController上显示UIAlertController强> 谢谢你能提供的任何帮助Ios 在swift 4中显示Firebase通知弹出窗口,ios,swift,firebase,apple-push-notifications,uialertcontroller,Ios,Swift,Firebase,Apple Push Notifications,Uialertcontroller,注意:解决方案在底部。 原版。 我按照firebase上的说明在iOS中设置推送通知。我确实成功地获得了手机通知,如果应用程序关闭,我会在手机顶部显示通知,但如果我在应用程序中,则不会显示通知。我在终端上看到了打印件,所以我知道它收到了通知 理想的功能是: 1) 如果当用户单击通知时,应用程序已关闭或处于后台,则会打开应用程序,然后会显示应用程序内弹出警报,通知中会显示“确定”按钮以单击 2) 如果应用程序位于前台,通知将显示为弹出警报,并单击“确定”按钮 下面是AppDelegate.swif
import UIKit
import GoogleMaps
import Sentry
import UserNotifications
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let userDefaults = UserDefaults.standard
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
VersionCheck.shared.IsUpdateRequired()
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
let message : [String : Any] = userInfo["aps"] as! [String : Any]
let messageAlert : [String : Any] = message["alert"] as! [String : Any]
let lBody : String = messageAlert["body"] as! String
let lTitle : String = messageAlert["title"] as! String
print("body 1 = \(lBody)") //this works!
print("title = \(lTitle)") //this works!
let alert = UIAlertController(title: lTitle, message: lBody, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil);
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let message : [String : Any] = userInfo["aps"] as! [String : Any]
let messageAlert : [String : Any] = message["alert"] as! [String : Any]
let lBody : String = messageAlert["body"] as! String
let lTitle : String = messageAlert["title"] as! String
print("body 2 = \(lBody)")
print("title = \(lTitle)")
let alert = UIAlertController(title: lTitle, message: lBody, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil);
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
let message : [String : Any] = userInfo["aps"] as! [String : Any]
let messageAlert : [String : Any] = message["alert"] as! [String : Any]
let lBody : String = messageAlert["body"] as! String
let lTitle : String = messageAlert["title"] as! String
print("body 3 = \(lBody)")
print("title = \(lTitle)")
let alert = UIAlertController(title: lTitle, message: lBody, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
completionHandler([UNNotificationPresentationOptions.alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)") //can use the id later to privent multiple popups of the same message
}
let message : [String : Any] = userInfo["aps"] as! [String : Any]
let messageAlert : [String : Any] = message["alert"] as! [String : Any]
let lBody : String = messageAlert["body"] as! String
let lTitle : String = messageAlert["title"] as! String
print("body 4 = \(lBody)")
print("title = \(lTitle)")
let alert = UIAlertController(title: lTitle, message: lBody, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)whenever a new token is generated.
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
}
解决方案:
我添加了PresentedViewController?并允许显示警报弹出窗口。
另外,通过将UIBackgroundFetchResults.newData添加到completionHandler,我能够在应用程序中显示通知
新代码如下所示
let alert = UIAlertController(title: lTitle, message: lBody, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.window?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)
completionHandler(UIBackgroundFetchResult.newData)