ios - 通知警报有问题

标签 ios swift firebase push-notification alert

所以这是我第一次尝试在应用程序上实现通知。我已经设法接收到它并在 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")
    }
}

可能有冗余代码..不是真的必要

从控制台:

Entire message [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%cef2e812cef2e812, AnyHashable("notification_type"): message, AnyHashable("params"): {"color":"#009687","conversation_id":"8","subject":"new voice message","sound":"default","icon":"https://voicemo.site/media/photos/users/img_2c9b5.jpg","title":"CabuZZ"}, AnyHashable("aps"): { "content-available" = 1; }]

最佳答案

1) 当应用处于后台时:

当应用程序处于后台时显示通知的正确格式在 aps 字典中为:

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

因此,在您的情况下,将 aps key 的有效负载更新为:

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

2) 当应用在前台时:

您将在以下函数中收到 userInfo 中的数据,您需要手动显示和处理 View 。当应用程序在前台时,iOS 将不会呈现 View 。

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

    // Handle your view here (app in foreground)

}

关于ios - 通知警报有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181656/

相关文章:

ios - 如何以编程方式从iOS设备上删除应用程序?

iphone - iOS SDK 编辑 PDF 添加图像

ios - AVPlayer没有声音

swift - 在 NSDictionary Swift 中访问项目时出现问题

ios - Swift - 从 facebook 登录中获取错误

firebase - PERMISSION_DENIED:权限不足或不足- flutter

ios - 随着 iOS 13 的发布, "Sign in with Apple"是强制性的

ios - 如何在 SwiftUI 中将 LocalizedStringKey 更改为 String

swift - Sprite Kit 的辅助功能(画外音)

swift - 如何观察然后从 firebase 数据库连续快速写入