Как освежить уведомление об уведомлении Firebase Push SwiftIOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Как освежить уведомление об уведомлении Firebase Push Swift

Сообщение Anonymous »

Я использую уведомление Firebase push в моем приложении, когда пользователь установил приложение в свое устройство в первый раз. Вызовет следующий метод. < /p>

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

//Firebase Configure
FirebaseApp.configure()

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

application.registerForRemoteNotifications()

return true
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
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) {

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

// Print full message.
print(userInfo)

completionHandler(UIBackgroundFetchResult.newData)
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken 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.

defaultValues.set(fcmToken, forKey: "FCMToken")
defaultValues.synchronize()

}
@available(iOS 10, *)

extension AppDelegate : UNUserNotificationCenterDelegate {

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

}

// MARK: - Push Notification MessagingDelegate methods.

extension AppDelegate: MessagingDelegate{

func messaging(_ messaging: Messaging, didReceiveRegistrationToken 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.

defaultValues.set(fcmToken, forKey: "FCMToken")
defaultValues.synchronize()

//Call Sending device info to api.
}

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {

defaultValues.set(fcmToken, forKey: "FCMToken")
defaultValues.synchronize()

//Call Sending device info to api.
Helper.shared.appDelegate.SendingDeviceInfo()
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Message data:", remoteMessage.appData)
}

}
< /code>

Когда пользователь нажимает кнопку входа в систему, я нажимаю на API.
Но моя проблема заключается в том, когда пользователь выходит в систему, и снова входит в систему API, но с токеном NIL FCM.
во время входа в систему я очищаю все данные по умолчанию. Код < /p>

func loggout(){
//logout and reset root controller - Delete all userdefaults data.

SVProgressHUD.dismiss()

//Clear All Default values
let domain = Bundle.main.bundleIdentifier!
defaultValues.removePersistentDomain(forName: domain)
defaultValues.synchronize()
setRootControllerBeforeLogin()
}
< /code>

Я отправляю токен FCM на сервер с помощью этого метода Я вызываю этот метод в кнопке входа в систему. < /p>

func SendingDeviceInfo(){
let fcmvalue = defaultValues.string(forKey: "FCMToken") ?? ""
let param:[String:Any] = ["registerID":fcmvalue]

WebService.shared.apiDataPostMethod(url: deviceInfoURL, parameters: param) { (response, error) in
if error == nil
{
print(param)
}else{
// print(error?.localizedDescription)
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/571 ... tion-swift
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»