Как получить push-уведомления из firebase, сохранить их в виде массива и опубликовать в UITableViewCell в swift 4 - PullRequest
0 голосов
/ 10 июня 2019
// App delegate:
import UIKit
import CoreData
import Firebase
import UserNotifications




@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

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

        application.registerForRemoteNotifications()



        FirebaseApp.configure()
        Messaging.messaging().delegate = self as? MessagingDelegate


        if let notification = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: AnyObject] {
            window?.rootViewController?.present(tableViewController2(), animated: true, completion: nil)
            notificationReceived(notification: notification as [NSObject : AnyObject])

        } else {
            application.registerForRemoteNotifications()
        } 

        return true

    }



    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.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
    // I tried parsing the JSON here
    private func parseRemoteNotification(notification:[String:AnyObject]) -> (String, String) {
         let aps = notification["aps"] as? [String:AnyObject]
              let alert = aps?["alert"] as? [String:AnyObject]
                let body = alert?["body"] as? String
                let title = alert?["title"] as? String





        return (title ?? "-", body ?? "-")
    }

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {



        // 1 in this attempt I tried to just access the contents and pass it as a variable into my tableviewController
        let userInfo = response.notification.request.content.userInfo
        print("MessageID: \(userInfo)")
        print(userInfo)

        let viewController = window?.rootViewController
        let view = viewController as? tableViewController2

     view?.title = response.notification.request.content.title
        view?.message = response.notification.request.content.body




       // completionHandler()



      completionHandler()
}
func notificationReceived(notification: [NSObject:AnyObject]) {
        let viewController = window?.rootViewController
        let view = viewController as? tableViewController2
            view?.addNotification(
                title: parseRemoteNotification(notification: notification as! [String : AnyObject]).0,
                body: parseRemoteNotification(notification: notification as! [String : AnyObject]).1)
    }

// в TableViewController: // я вызвал эту функцию, чтобы разобрать JSON из appDelegate в // tableviewcontroller
func addNotification (название: строка, тело: строка) { DispatchQueue.main.async { let indexPath = [IndexPath (item: self.notifications.count, section: 0)] self.notifications.append ((название, тело)) self.tableView.insertRows (at: indexPath, с: .bottom) } }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {



        let view = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell




       (view.viewWithTag(1) as? UILabel)?.text = notifications[indexPath.row].0
       (view.viewWithTag(2) as? UILabel)?.text = notifications[indexPath.row].1
        return view
    }
...