Firebase-推送通知-没有像预期的那样工作



为了试用Firebase的推送通知,我一直在遵循以下三个文档:一、二、三和四。

我有一个问题,但在问之前;这是我能看到的:

当我的应用程序在前台并发送通知时,只调用此函数:

userNotificationCenter(_:willPresent:withCompletionHandler:)

如果我点击通知,那么这个也被称为:

userNotificationCenter(_:didReceive:withCompletionHandler:)

当我的应用程序在后台并发送通知时,不会调用任何内容。

如果我点击通知,那么这个被称为:

userNotificationCenter(_:didReceive:withCompletionHandler:)

由于这种情况,whithout不得不做出反应(通过点击通知(;我可以让应用程序在前台收到通知时执行一些有用的操作,使用userNotificationCenter(_:willPresent:withCompletionHandler:(函数。

另一方面,在后台,如果用户点击通知,我只能让应用程序在通知到达时执行一些有用的操作。

即使用户没有反应,我也有办法让应用程序执行一些有用的操作吗?

这是我目前拥有的相关代码:

import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {
granted, error in
if error != nil {print("Error: (error!)")}
if granted {
DispatchQueue.main.async
{application.registerForRemoteNotifications()}
}
})
FirebaseApp.configure()
.......
return true
}

func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(#function)
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: (messageID)")
}
// Print full message.
print(userInfo)
}

func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(#function)
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: (messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}

有关信息,我使用的是Xcode版本10.1、iOS 12.1和Swift 4.2。

swift 4.2,Xcode 10.0,IOS 12.0

import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
let setting = UIUserNotificationSettings(types: type, categories: nil)
UIApplication.shared.registerUserNotificationSettings(setting)
UIApplication.shared.registerForRemoteNotifications()
}
} else {
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
let setting = UIUserNotificationSettings(types: type, categories: nil)
UIApplication.shared.registerUserNotificationSettings(setting)
UIApplication.shared.registerForRemoteNotifications()
}
application.registerForRemoteNotifications()
if(FIRApp.defaultApp() == nil){
FIRApp.configure()
}
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification(notification:)),
name: NSNotification.Name.firInstanceIDTokenRefresh,
object: nil)
return true
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo as? NSDictionary
_ = UIStoryboard(name: "Main", bundle: nil)
let appdelegate = UIApplication.shared.delegate as! AppDelegate
let aps = userInfo?["aps"] as! NSDictionary
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device Token", deviceTokenString)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
}
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
let appdelegate = UIApplication.shared.delegate as! AppDelegate
let aps = data["aps"] as! NSDictionary
let state = UIApplication.shared.applicationState
if state == .background {
}
if state == .active {
}
}
//MARK: Notification Center Call
func callNotificationCenter(){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadData"), object: nil)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
// start firebase
@objc func tokenRefreshNotification(notification: NSNotification) {
let refreshedToken = FIRInstanceID.instanceID().token()
print(refreshedToken)
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. (error?.localizedDescription ?? "")")
} else {
print("Connected to FCM")
}
}
}

相关内容

  • 没有找到相关文章

最新更新