Swift ios在应用程序内触发推送通知,而不是通过firebase控制台

时间:2018-03-28 02:23:34

标签: ios swift notifications uilocalnotification

大家好,大家好,我想问一下,如果只是单击一个按钮就可以触发我的ios应用程序中的推送通知。我的推送通知工作正常通过firebase控制台发送,但我不知道在应用程序内部使其成为可能。并且也是适用于此的alamofire。 下面是我的应用程序委托代码顺便说一下你可以使用它它可以在前台或后台收到消息。

的appdelegate

//
//  AppDelegate.swift
//
//
//  Created by High Sierra User on 24/3/18.
//


import UIKit
import CoreData
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate{

    var window: UIWindow?


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

        if #available(iOS 9.0, *) {
            // For iOS 10 display notification (sent via APNS)
            //            UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
            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()

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        if UserDefaults.standard.bool(forKey: "isLoggedIn") {
            let  menuVC = storyBoard.instantiateViewController(withIdentifier: "MenuCollectionViewController") as! MenuCollectionViewController

            let nvc: UINavigationController = UINavigationController(rootViewController: menuVC)
            nvc.navigationBar.isHidden =  true

            self.window?.rootViewController = nvc
            self.window?.makeKeyAndVisible()

        } else {

            self.showLoginScreen()
        }


        FirebaseApp.configure()

        let notificationTypes : UIUserNotificationType = [UIUserNotificationType.alert , UIUserNotificationType.badge, UIUserNotificationType.sound]
        let notificatiognSettings = UIUserNotificationSettings(types: notificationTypes,categories : nil)

        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificatiognSettings)

        return true
    }

    //    func userNotificationCenter(_ center: UNUserNotificationCenter,
    //                                willPresent notification: UNNotification,
    //                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    //        let userInfo = notification.request.content.userInfo
    //
    //        // With swizzling disabled you must let Messaging know about the message, for Analytics
    //        Messaging.messaging().appDidReceiveMessage(userInfo)
    //        // Print message ID.
    //        if let messageID = userInfo["gcmMessageIDKey"] {
    //            print("Message ID: \(messageID)")
    //        }
    //        print(userInfo)
    //
    //        UIApplication.shared.applicationIconBadgeNumber = 1
    //
    //
    //        completionHandler([.alert, .badge, .sound])
    //
    //    }


    // 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

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo["gcmMessageIDKey"] {
            print("Message ID: \(messageID)")
        }
        //            var badge = 0
        //            UIApplication.shared.applicationIconBadgeNumber = badge

        completionHandler([.alert, .badge, .sound])
        // Change this to your preferred presentation option
        // completionHandler([])
    }

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

        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo["gcmMessageIDKey"] {
            print("Message ID: \(messageID)")
        }
        switch response.actionIdentifier {
        case "action1":
            print("Action First Tapped")
        case "action2":
            print("Action Second Tapped")
        default:
            break
        }

        // Print full message.
        print(userInfo)
        Messaging.messaging().appDidReceiveMessage(userInfo)
        completionHandler()
    }


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

        //        print("MessageID: \(userInfo["gcm_message_id"])")
        //        print(userInfo)

        if let message = userInfo["gcm_message_id"] {
            print("MessageID: \(message)")
        }

        print(userInfo)



    }

    func showLoginScreen()
    {

        UserDefaults.standard.set(false, forKey: "isLoggedIn")
        UserDefaults.standard.synchronize()


        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController

        let nvc: UINavigationController = UINavigationController(rootViewController: loginViewController)
        nvc.navigationBar.isHidden = true
        self.window?.rootViewController = nvc
        self.window?.makeKeyAndVisible()

    }

    func applicationWillResignActive(_ application: UIApplication) {

    }

    func applicationDidEnterBackground(_ application: UIApplication) {

    }

    func applicationWillEnterForeground(_ application: UIApplication) {

    }

    func applicationDidBecomeActive(_ application: UIApplication) {

    }

    func applicationWillTerminate(_ application: UIApplication) {

    }


    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "FridgeBoard")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {

                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()


    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {

                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }



}

0 个答案:

没有答案