Я использую уведомление 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
Как освежить уведомление об уведомлении Firebase Push Swift ⇐ IOS
Программируем под IOS
-
Anonymous
1753609244
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)
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/57105606/how-to-refresh-the-firebase-push-notification-swift[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия