推送通知在前台不起作用
Posted
技术标签:
【中文标题】推送通知在前台不起作用【英文标题】:Push notification not working in foreground 【发布时间】:2017-11-16 07:51:22 【问题描述】:当我的应用程序运行时,我从 firebase 发送了通知,调用了 UNUserNotification
委托方法,我收到了通知并且它显示在顶部,但是当我从我的 API 服务器发送通知时,
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)
firebase 委托正在调用,我可以获取数据,但通知未显示在顶部。
我的代码如下:
func registerForPushNotification(_ application: UIApplication)
if #available(ios 10.0, *)
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: _, _ in )
// For iOS 10 data message (sent via FCM
//Messaging.messaging().delegate = self
else
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
application.applicationIconBadgeNumber = 0
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
print("device token %@",deviceToken)
var deviceTokenString = String(format: "%@", deviceToken as CVarArg)
deviceTokenString = deviceTokenString.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
deviceTokenString = deviceTokenString.replacingOccurrences(of: " ", with: "")
print(deviceTokenString)
//saveDeviceIdinDefaults(deviceId: deviceTokenString)
Messaging.messaging().apnsToken = deviceToken
// InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.sandbox)
// InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.prod)
// The callback to handle data message received via FCM for devices running iOS 10 or above.
func application(received remoteMessage: MessagingRemoteMessage)
print(remoteMessage.appData)
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
print("Userinfo \(response.notification.request.content.userInfo)")
if response.actionIdentifier == UNNotificationDismissActionIdentifier
print ("Message Closed")
else if response.actionIdentifier == UNNotificationDefaultActionIdentifier
print ("App is Open")
// Else handle any custom actions. . .
completionHandler()
// print("Userinfo \(response.notification.request.content.userInfo)")
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error)
print("Failed to register: \(error)")
@objc func tokenRefreshNotification(_ notification: NSNotification)
// print("refresh token call")
guard let contents = InstanceID.instanceID().token()
else
return
// let refreshedToken = FIRInstanceID.instanceID().token()!
let refreshedToken = contents//InstanceID.instanceID().token()
print("InstanceID token: \(refreshedToken)")
Constant.saveFcmToken(fcmToken: refreshedToken, key: "deviceid")
// UserDefaults.standard.set(refreshedToken, forKey: "deviceid")
print("InstanceID token: \(contents)")
connectToFcm()
func connectToFcm()
// Won't connect since there is no token
guard InstanceID.instanceID().token() != nil else
print("FCM: Token does not exist.")
return
// Disconnect previous FCM connection if it exists.
Messaging.messaging().disconnect()
Messaging.messaging().connect (error) in
if error != nil
print("FCM: Unable to connect with FCM. \(error.debugDescription)")
else
print("Connected to FCM.")
// [START refresh_token]
//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String)
// FCM token updated, update it on Backend Server
print("Firebase registration token: \(fcmToken)")
saveDeviceIdinDefaults(deviceId: fcmToken)
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)
print("remoteMessage: \(remoteMessage)")
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound,.badge],
completionHandler: (granted,error) in
NotificationCenter.default.post(name: NSNotification.Name("GetPollsUpdateNotification"), object: nil)
//self.isGrantedNotificationAccess(data: remoteMessage.appData)
)
// let notifiDict = remoteMessage.appData as! [String:String]
// print(notifiDict)
// let title = notifiDict["title"]
// let message = notifiDict["message"]
// let image = notifiDict["image"]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
print(userInfo)
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any])
print(userInfo)
if application.applicationState == .active
//write your code here when app is in foreground
else
//write your code here for other state
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
completionHandler([UNNotificationPresentationOptions.alert])
let userInfo = notification.request.content.userInfo as! NSDictionary
print("\(String(describing: userInfo))")
print(notification.description)
谁能帮帮我?
【问题讨论】:
当应用程序在前台时,推送通知根本不会显示。如果适合您的应用,您可以在回调被调用时显示自己的通知。 【参考方案1】:我相信处理这个问题的方法是使用以下委托方法:
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
completionHandler([.alert, .sound, .badge])
希望这会有所帮助。
【讨论】:
以上是关于推送通知在前台不起作用的主要内容,如果未能解决你的问题,请参考以下文章