如何提示用户接受AppDelegate之外的推送通知?
问题描述:
我的应用程序加载到视图控制器中,告诉用户为什么他们应该接受推送通知。直到他们按下此视图控制器上的继续按钮后,我才希望它们接受推送通知。这意味着我需要将代码包含在我的初始视图控制器中的某处,我们称之为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)
}
}
}
答
你可以只移动FIRApp.configure()
,你需要问的授权后的代码;你可以得到应用与UIApplication.shared
答
有关推送通知,一旦你打电话application.registerForRemoteNotifications()
会出现提示的引用,因此,在调用这个函数时,你想你会显示提示。
要访问您的UIApplication您可以在Swift2
使用Swift3UIApplication.shared
或
UIApplication.sharedApplication()