当我们想要实现Firebase Cloud Messaging时,我们首先必须请求用户的通知权限。从Firebase文档中,他们建议在didFinishLaunchingWithOptions
上的Appdelegate中实现以下代码行:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
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()
return true
}
但是如果把这些代码放在appDelegate中,在用户打开我的应用程序后,弹出的请求权限的警报将立即显示。
如果我把这些代码移到VC中,那么application
就不可用了,因为application
来自didFinishLaunchingWithOptions
。然后是messagingDelegate.我不确定。你能帮我重写这些代码,但如果它不是在AppDelegate?
2条答案
按热度按时间ycl3bljg1#
我在iOS 10.3.3设备上进行测试,直到我将
UNUserNotificationCenter
的委托设置为UIApplication.shared.delegate as? UNUserNotificationCenterDelegate
,才将AppDelegate
中的实现委托设置为空委托。但在当前视图控制器中实现空委托并不起作用。AppDelegate.swift:
下面是我的视图控制器中的方法:
当然,你必须在
didFinishLaunchingWithOptions
方法中保留FirebaseApp.configure()
。稍后编辑:您可能会收到关于从主线程调用
registerForRemoteNotifications()
的警告,因此我调整了代码以实现这一点。iezvtpos2#
添加类
添加到您喜欢的VC