gpt4 book ai didi

ios - 推送通知在前台不起作用

转载 作者:行者123 更新时间:2023-11-28 07:58:17 25 4
gpt4 key购买 nike

当我的应用程序运行时,我从 firebase 发送通知,调用 UNUserNotification 委托(delegate)方法,我收到通知并显示在顶部,但是当我从我的 API 服务器发送通知时,

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)  

firebase 委托(delegate)正在调用,我可以获取数据,但通知未显示在顶部。

我的代码如下:

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)
}

有人能帮帮我吗?

最佳答案

我认为处理此问题的方法是使用以下委托(delegate)方法:

 @available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

completionHandler([.alert, .sound, .badge])

}

希望这对您有所帮助。

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

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