1

アプリがバックグラウンドまたは一時停止されたときに呼び出される基本的な関数をここに実装しようとしています。

実際には、1 日に約 5 件の送信を目指しているため、Apple が私たちの利用を抑制してはなりません。

firebase と userNotifications を使用する以下のものをまとめました。今のところ、それは私のアプリ デリゲートにあります。

import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var backgroundSessionCompletionHandler: (() -> Void)?


    lazy var downloadsSession: Foundation.URLSession = {
        let configuration = URLSessionConfiguration.background(withIdentifier: "bgSessionConfiguration")
        configuration.timeoutIntervalForRequest = 30.0
        let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
        return session
    }()



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FIRApp.configure()
        if #available(iOS 10.0, *) {
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
        let token = FIRInstanceID.instanceID().token()!
        print("token is \(token) < ")

        return true
    }



    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void){
           print("in handleEventsForBackgroundURLSession")
           _ = self.downloadsSession
           self.backgroundSessionCompletionHandler = completionHandler
    }

    //MARK: SyncFunc

    func startDownload() {
        NSLog("in startDownload func")

        let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
        guard let url = URL(string: todoEndpoint) else {
            print("Error: cannot create URL")
            return
        }

        // make the request
        let task = downloadsSession.downloadTask(with: url)
        task.resume()
        NSLog(" ")
        NSLog(" ")

    }

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession){
        DispatchQueue.main.async(execute: {
            self.backgroundSessionCompletionHandler?()
            self.backgroundSessionCompletionHandler = nil
        })
    }

    func application(_ application: UIApplication,  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],  fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        NSLog("in didReceiveRemoteNotification")
        NSLog("%@", userInfo)
        startDownload()

        DispatchQueue.main.async {
            completionHandler(UIBackgroundFetchResult.newData)
        }
    }

}

@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
        // Print message ID.
        //print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
        startDownload()  

             DispatchQueue.main.async {
                completionHandler(UNNotificationPresentationOptions.alert)
             }          
    }
    */
}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}

extension AppDelegate: URLSessionDownloadDelegate {
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
        NSLog("finished downloading")
    }
}

結果は次のとおりです。

アプリがフォアグラウンドにある場合:

  1. 「startDownload 関数で」ログを取得します

  2. 「ダウンロードが完了しました」というログが表示されます。

アプリがバックグラウンドの場合:

  1. 「startDownload 関数で」ログを取得します

  2. 「ダウンロードが完了しました」というログが表示されません。

  3. サイレンサーが機能していません。つまり、アプリがバックグラウンドになっている場合でも、トレイに通知が表示されます。

Postman を使用してリクエストを送信し、次のペイロードを試しましたが、コンソール エラーが発生しました'FIRMessaging receiving notification in invalid state 2'

{
    "to" : "Server_Key", 
    "content_available" : true,
    "notification": {
    "body": "Firebase Cloud Message29- BG CA1"
  }
}

バックグラウンド フェッチとリモート通知の機能を設定しています。アプリはSwift 3で書かれており、最新のFirebaseを使用しています

編集: コメントごとに funcs を含めるように AppDelegate を更新しました

4

1 に答える 1