gpt4 book ai didi

ios - 后台推送通知不起作用 iOS12 Swift4.2

转载 作者:可可西里 更新时间:2023-11-01 01:07:34 25 4
gpt4 key购买 nike

我已经通过 firebase 实现了推送通知。无法从后台获取通知。在我的 App 委托(delegate)中包含以下代码,

class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
sleep(3)
IQKeyboardManager.shared.enable = true

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 })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true

UIApplication.shared.registerForRemoteNotifications()
FirebaseApp.configure()

return true
}

func applicationWillResignActive(_ application: UIApplication) {

}

func applicationDidEnterBackground(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = true

}

func applicationWillEnterForeground(_ application: UIApplication) {

}

func applicationDidBecomeActive(_ application: UIApplication) {

}

func applicationWillTerminate(_ application: UIApplication) {

}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")

let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Message Data", remoteMessage.appData)

}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print message ID.
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) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler(UIBackgroundFetchResult.newData)
}
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

// Change this to your preferred presentation option
completionHandler([.alert])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler()
}

}

并在收到远程通知时获取消息数据的打印

Message Data [AnyHashable("from"): 459345502087, AnyHashable("collapse_key"): www.rwdev.com.TravelSheriff2.1, AnyHashable("notification"): {
body = "Notifications ";
e = 1;
tag = "campaign_collapse_key_4509884114250587926";
title = "Travel Sheriff ";
}]

但是我无法在后台和前台收到推送通知。即使在应用程序处于后台时也无法打印“消息数据”。(注意:请不要想出以前的堆栈溢出链接,答案已经尝试了大部分..没有解决..)

最佳答案

嘿@Aleesha 使用请求标识符。我在下面给您示例,请遵循代码,我希望它有效。

//MARK:- USER NOTIFICATION DELEGATE

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
print(notification.request.content.userInfo)

if notification.request.identifier == "rig"{
completionHandler( [.alert,.sound,.badge])
}else{
completionHandler([.alert, .badge, .sound])
}

}



func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
//Handle the notification
completionHandler(
[UNNotificationPresentationOptions.alert,
UNNotificationPresentationOptions.sound,
UNNotificationPresentationOptions.badge])
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

Messaging.messaging().apnsToken = deviceToken
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print(deviceTokenString)

}


func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

print(userInfo)

switch application.applicationState {
case .active:
let content = UNMutableNotificationContent()
if let title = userInfo["title"]
{
content.title = title as! String
}
if let title = userInfo["text"]
{
content.body = title as! String
}
content.userInfo = userInfo
content.sound = UNNotificationSound.default()

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
let request = UNNotificationRequest(identifier:"rig", content: content, trigger: trigger)

UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(request) { (error) in
if let getError = error {
print(getError.localizedDescription)
}
}
case .inactive:
break
case .background:
break
}



}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("i am not available in simulator \(error)")
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let token = Messaging.messaging().fcmToken
print("FCM token: \(token ?? "")")

}

关于ios - 后台推送通知不起作用 iOS12 Swift4.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54416388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com