我想使用willPresent
方法在前台发送通知,但在后台不发送。但是,通知始终显示。
这是我的appdelegate
:
import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging
import RxSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
let disposeBag = DisposeBag()
override init() {
super.init()
}
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool
{
FirebaseApp.configure()
if #available(iOS 10.0, *) {
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
Messaging.messaging().useMessagingDelegateForDirectChannel = true
// 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
self.getNotificationSettings()
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
// Check user logged
if let accessToken = UserDefaults.standard.value(forKey : "AccessToken") as? String, accessToken.count > 2 {
window?.rootViewController = Assembler.createMainViewController()
} else {
window?.rootViewController = Assembler.createAuthViewController()
}
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void)
{
Messaging.messaging().appDidReceiveMessage(response.notification.request.content.userInfo)
(window?.rootViewController as? UITabBarController)?.selectedIndex = 2
UIApplication.shared.applicationIconBadgeNumber = 0
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
{
print(userInfo)
if let accessToken = UserDefaults.standard.value(forKey : "AccessToken") as? String, accessToken.count > 2, application.applicationState == .active {
Messaging.messaging().appDidReceiveMessage(userInfo)
guard let aps = userInfo["aps"] as? [String: AnyObject], let body = aps["alert"] as? String else {
completionHandler(.failed)
return
}
print(body)
UIApplication.shared.applicationIconBadgeNumber += 1
let notificationCenter = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.body = body
let request = UNNotificationRequest(identifier: "FIRST_LOCAL_NOTIFICATION", content: content, trigger: nil)
notificationCenter.add(request) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
print(notification.request.content)
let options = UNNotificationPresentationOptions(arrayLiteral: .alert, .sound)
completionHandler(options)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
APIManager.shared.rx_registerFCMWith(token: result.token)
.subscribe(onNext: { (val) in
print("FCM REGISTRATION HAS FINISHED SUCCESSUFULLY")
}, onError: { (error) in
print("FCM REGISTRATION HAS FAILED \(error.localizedDescription)")
}).disposed(by: self.disposeBag)
}
}
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
guard let data = try? JSONSerialization.data(withJSONObject: remoteMessage.appData, options: .prettyPrinted),
let prettyPrinted = String(data: data, encoding: .utf8) else {
return
}
UIApplication.shared.applicationIconBadgeNumber += 1
print("Received direct channel message:\n\(prettyPrinted)")
}
private func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
}