2

我的應用程序加載到視圖控制器中,告訴用戶爲什麼他們應該接受推送通知。直到他們按下此視圖控制器上的繼續按鈕後,我才希望它們接受推送通知。這意味着我需要將代碼包含在我的初始視圖控制器中的某處,我們稱之爲BeforePromptController。我在使用Firebase以防萬一。如何提示用戶接受AppDelegate之外的推送通知?

這是我在AppDelegate中的工作代碼(但是我想對其進行更改,以便在用戶按下BeforePromptController中的Continue按鈕後發生提示)。我試着只包含的AppDelegate這裏的重要組成部分..

import UIKit 
import Firebase 
import FirebaseMessaging 
import UserNotifications 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate { 

    var window: UIWindow? 

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

     FIRApp.configure() 

     if #available(iOS 10.0, *) { 
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] 
      UNUserNotificationCenter.current().requestAuthorization(
       options: authOptions, 
       completionHandler: {_, _ in }) 

      // For iOS 10 display notification (sent via APNS) 
      UNUserNotificationCenter.current().delegate = self 
      // For iOS 10 data message (sent via FCM) 
      FIRMessaging.messaging().remoteMessageDelegate = self 

     } else { 
      let settings: UIUserNotificationSettings = 
       UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
      application.registerUserNotificationSettings(settings) 
     }   

     application.registerForRemoteNotifications() 

     return true 
    } 



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

     if application.applicationState == UIApplicationState.active { 

      var pushNotificationMessage = "" 
      if let aps = userInfo["aps"] as? NSDictionary { 
       if let alert = aps["alert"] as? NSDictionary { 
        if let message = alert["message"] as? NSString { 
         pushNotificationMessage = message as String 
        } 
       } else if let alert = aps["alert"] as? NSString { 
        pushNotificationMessage = alert as String 
       } 
      } 

      let notificationAlert = UIAlertController(title: nil, message: pushNotificationMessage, preferredStyle: .alert) 

      let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { 
       (alert: UIAlertAction!) -> Void in 
      }) 
      defaultAction.setValue(Constants.activePushNotificationOKColor, forKey: "titleTextColor") 

      notificationAlert.addAction(defaultAction) 
      self.window?.rootViewController?.present(notificationAlert, animated: true, completion: nil) 
     } 
    } 
} 

回答

1

你可以只移動FIRApp.configure(),你需要問的授權後的代碼;你可以得到應用與UIApplication.shared

0

有關推送通知,一旦你打電話application.registerForRemoteNotifications()會出現提示的引用,因此,在調用這個函數時,你想你會顯示提示。

要訪問您的UIApplication您可以在Swift2

使用Swift3 UIApplication.sharedUIApplication.sharedApplication()
相關問題