Возникла проблема с уведомлением об уведомлении - PullRequest
0 голосов
/ 04 мая 2018

Итак, это мой первый раз, когда я пытаюсь реализовать уведомление в приложении. Мне удалось получить его и увидеть его в userInfo, но я не получаю его как предупреждение сверху, когда получаю его. из облачных сообщений от Firebase.

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import UserNotifications
import Firebase
import FirebaseMessaging
import NotificationCenter
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)



        FirebaseApp.configure()

        let userToken = userDefaults.value(forKey: "user_token")
        if userToken == nil {
            //User is logged in
            showLoginVC()
        }
        else {
            //Show login Screen
            showHomeVC()

            Helper.registerDevice()
        }
        return true
    }

    func showLoginVC() {

        FBSDKLoginManager().logOut()

        let loginViewController = storyboard.instantiateViewController(withIdentifier: "loginVC")

        appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
        appDelegate.window?.rootViewController = loginViewController
        appDelegate.window?.makeKeyAndVisible()
    }

    func showHomeVC() {

//        let voiceMoRecents = storyboard.instantiateViewController(withIdentifier: "MainVC")
//                appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
//                appDelegate.window?.rootViewController = voiceMoRecents
//                appDelegate.window?.makeKeyAndVisible()

        let swRevealViewController = storyboard.instantiateViewController(withIdentifier: "SWRevealViewController")

        appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
        appDelegate.window?.rootViewController = swRevealViewController
        appDelegate.window?.makeKeyAndVisible()

        if userDefaults.value(forKey: "deviceToken") == nil {
            // MARK:  PushNotification
            registerForPushNotifications()
            UNUserNotificationCenter.current().delegate = self
            GlobalMainQueue.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        FBSDKAppEvents.activateApp()
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    // MARK:  Facebook Login
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
    }


    // MARK:  PUSH NOTIFICATION FUNCTIONS

    func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            print("Permission granted: \(granted)")

            guard granted else { return }
            self.getNotificationSettings()
        }
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        if let instanceIdToken = InstanceID.instanceID().token() {
            print("Device token which is good to use with FCM \(instanceIdToken)")
            userDefaults.setValue(instanceIdToken, forKey: "deviceToken")
        }

        if userDefaults.value(forKey: "callToRegisterDevice") != nil {
            Helper.registerDevice()
            userDefaults.removeObject(forKey: "callToRegisterDevice")
        }
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Fail to register for remote nottification \(error)")
    }

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

        print(" Entire message \(userInfo)")
        print("Article avaialble for download: \(userInfo)")

        let state : UIApplicationState = application.applicationState
        switch state {
        case UIApplicationState.active:
            print("If needed notify user about the message")
        case UIApplicationState.inactive:
            print("UIApplicationState.inactive")
        case UIApplicationState.background:
            print("UIApplicationState.background")
        default:
            print("Run code to download content")
        }

        completionHandler(UIBackgroundFetchResult.newData)
    }

    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
                Helper.registerDevice()
            })
        }
    }


    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "VoiceMe")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    // iOS10+, called when presenting notification in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print("[UserNotificationCenter] applicationState:  willPresentNotification: \(userInfo)")
        //TODO: Handle foreground notification
        completionHandler([.alert])
    }

    // iOS10+, called when received response (default open, dismiss or custom action) for a notification
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print("[UserNotificationCenter] applicationState:  didReceiveResponse: \(userInfo)")
        //TODO: Handle background notification
        completionHandler()
    }
}

extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
    }
}


    class func registerDevice() {
    if let deviceToken = userDefaults.value(forKey: "deviceToken") as? String {
        let callUrl = URL(string: Helper.apiUrl + "auth/register-device")
        let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"]
        let data2send: Dictionary<String, Any> = ["device_token" : deviceToken,
                                                  "user_token" : userDefaults.value(forKey: "user_token") as! String,
                                                  "source":"ios",
                                                  "version":"\(String(describing: appVersion!))"]

        Alamofire.request(callUrl!, method: .post, parameters: data2send).validate().responseJSON { response in
            print(response)
            if response.result.isSuccess {
                let resultObj = JSON(response.result.value!)
                if let _ = resultObj["data"].rawString(){
                    DispatchQueue.main.async {
                        print("device registered successfully")
                    }
                }
            } else {
                print("Error : \(String(describing: response.error))")
            }
        }
    } else {
        userDefaults.setValue("yes", forKey: "callToRegisterDevice")
    }
}

Возможно иметь избыточный код .. не очень нужно

с консоли:

Полное сообщение [AnyHashable ("data"): {"duration": "1346", "updated_at": "2018-05-04 18:53:54", "type_type": 2, "journal_id": " 8 "," owner_id ": 13," status_name ":" Read "," message_token ":" 2018050421535268819 "," creation_at ":" 2018-05-04 18:53:54 "," message_id ": 156," url ":" https://voicemo.site/media/files/8/201805042153526881915613.amr"}, AnyHashable ("push_id"): ios_fIpMjYVprDSxrp3LWbV4QOIms452WUsT, AnyHashable ("gcm.message_id"): 0: 1525460034407947% cef2e812cef2e812, Any "" color: "типа": любой " : "# 009687", "journal_id": "8", "subject": "новое голосовое сообщение", "sound": "default", "icon": "https://voicemo.site/media/photos/users/img_2c9b5.jpg","title":"CabuZZ"}, AnyHashable (" aps "): { «контент-доступный» = 1; }]

1 Ответ

0 голосов
/ 07 мая 2018

1) Когда приложение в фоновом режиме:

Правильный формат для отображения уведомления, когда приложение в фоновом режиме находится в aps словаре как:

{
  "aps": {
      "alert": {
          "title": "",
          "subtitle": "",
          "body": “”
      },
      "badge": 1,
      "sound": "default",
      "content-available": 1,
  }
  // Other data here...
}

Итак, в вашем случае обновите полезную нагрузку для ключа aps следующим образом:

  "aps": {
      "alert": {
          "title": "CabuZZ",
          "body": “new voice message”
      },
      "badge": 1,
      "sound": "default",
      "content-available": 1,
  }

2) Когда приложение находится на переднем плане:

Вы получите данные в userInfo в следующей функции, вам нужно показать и обработать вид вручную. iOS не будет отображать вид, когда приложение находится на переднем плане.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

    // Handle your view here (app in foreground)

}
...