我的应用加载到视图控制器中,该控制器告诉用户为什么他们应该接受推送通知。直到他们按下此视图控制器上的"继续"按钮后,我才希望提示他们接受推送通知。这意味着我需要在初始视图控制器中的某个位置包含代码,我们将其称为 BeforePromptController。我正在使用Firebase以防万一。
这是我在AppDelegate中的工作代码(但是我想更改它,以便在用户按下BeforePromptController中的"继续"按钮后出现提示(。我试图在这里只包含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,您可以使用 Swift3 中的UIApplication.shared
或 Swift2 中的UIApplication.sharedApplication()