Как вызвать API, когда приложение завершено в push-уведомлении iOS Swift?

одно решение будет проверять существование папки

function myLs() {
    LIST=""
    folder=$1
    [ "x$folder" = "x" ] && folder="."
    [ -d $folder ] && LIST=`ls $folder`
    echo $LIST
}

Таким образом, bash не сбой, если $folder не существует

3
задан Dávid Pásztor 17 January 2019 в 13:54
поделиться

3 ответа

Проверьте ссылку ниже, это то, что вам нужно.

https://samwize.com/2015/08/07/how-to-handle-remote-notification-with-background-mode-enabled/

активировать фоновый режим для push-уведомлений. Полный процесс был объяснен в вышеупомянутой статье.

0
ответ дан Khushal Dugar 17 January 2019 в 13:54
поделиться

Согласно рекомендациям Apple, вы можете получать push-уведомления как для фона, так и для состояния переднего плана, но когда дело доходит до состояния завершения, яблоко не позволяет автоматически открывать приложение или выполнять какие-либо действия. операции, если вы не запустите приложение через уведомление.

Хотя вы можете обрабатывать уведомления во время завершения, используя параметры запуска во время запуска приложения.

Пример кодирования:

В вашей библиотеке импорта баз данных импорта AppDelegate.swift

import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications

Всякий раз, когда запуск приложения регистрируется для push добавьте следующие строки кода в didFinishLaunchingWithOptions

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    registerForPushNotifications(application: application)
    handleNotificationWhenAppIsKilled(launchOptions)
    return true
}

func handleNotificationWhenAppIsKilled(_ launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
    // Check if launched from the remote notification and application is close
    if let remoteNotification = launchOptions?[.remoteNotification] as?  [AnyHashable : Any] {
        // Handle your app navigation accordingly and update the webservice as per information on the app.
    }
}

Добавьте методы расширения appDelegate, чтобы зарегистрироваться для удаленного уведомления и получить токен устройства из APNS

//MARK: - Notifications related...
extension AppDelegate {
    func registerForPushNotifications(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()
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", [112]) }.joined()
        let savedAPNSToken = UserDefaults.standard.object(forKey: "savedAPNSToken") as? String
        if savedAPNSToken != token {
            UserDefaults.standard.set(token, forKey: "savedAPNSToken")
            UserDefaults.standard.synchronize()
            Messaging.messaging().apnsToken = deviceToken
        }
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error.localizedDescription)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        completionHandler(UIBackgroundFetchResult.newData)
    }

}

Используйте следующие методы центра уведомлений для обработки уведомлений в основном и фоновом состояниях:

// MARK: - UNUserNotificationCenterDelegate
@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
        completionHandler([.alert])
    }


    /// Handle tap on the notification banner
    ///
    /// - Parameters:
    ///   - center: Notification Center
    ///   - response: Notification response
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo
        completionHandler()
    }

Обновление токена Firebase:

extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        // Note: This callback is fired at each app startup and whenever a new token is generated.
        let savedFCMToken = UserDefaults.standard.object(forKey: "savedFCMToken") as? String
        if savedFCMToken != fcmToken {
            UserDefaults.standard.set(fcmToken, forKey: "savedFCMToken")
            UserDefaults.standard.synchronize()
            // Update FCMToken to server by doing API call...
        }
    }
}
0
ответ дан Jarvis The Avenger 17 January 2019 в 13:54
поделиться

У нас есть опция, называемая проверкой молчаливых уведомлений, по ссылке ниже https://medium.com/@m.imadali10/ios-silent-push-notifications-84009d57794c

0
ответ дан Rajasekaran Gopal 17 January 2019 в 13:54
поделиться
Другие вопросы по тегам:

Похожие вопросы: