【问题标题】:Having issue with the alert of notification通知警报有问题
【发布时间】:2018-05-04 19:06:57
【问题描述】:

所以这是我第一次尝试在应用程序上实现通知..我已经设法接收它并在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","status_type":2,"conversation_id":" 8","owner_id":13,"status_name":"Read","message_token":"2018050421535268819","created_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% notification_type"): message, AnyHashable("params"): {"color":"#009687","conversation_id":"8","subject":"新语音消息","sound":"default","图标":"https://voicemo.site/media/photos/users/img_2c9b5.jpg","title":"CabuZZ"}, AnyHashable("aps"): { “内容可用”= 1; }]

【问题讨论】:

  • “我没有从顶部收到它作为警报” - 你的意思是当你在前台时,你没有收到任何警报/ UI 来通知?
  • 正是..还有背景..

标签: ios swift firebase push-notification alert


【解决方案1】:

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)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多