iOS内使用谷歌推送相关的代码
2022-02-15 本文已影响0人
陈藩
1.添加头文件
import Firebase
import FirebaseMessaging
2.遵守协议
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate,MessagingDelegate{
3.appDelegate内的代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 谷歌推送相关
self.setUpFirebaseConfigure(application)
}
4.协议方法
func setUpFirebaseConfigure(_ application:UIApplication){
FirebaseApp.configure()
Messaging.messaging().delegate = self
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { ret, error in
print("ret == \(ret)")
print("error == \(error)")
}
application.registerForRemoteNotifications()
}
//获取token
internal func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("deviceToken==\(deviceToken)")
Messaging.messaging().apnsToken = deviceToken
}
//注册token
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
let dataDict: [String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: dataDict
)
}
5.其他相关方法
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfor = response.notification.request.content.userInfo
}