我正在尝试使用Firebase进行推送通知;首先,我遵循以下文档: https://www.appcoda.com/firebase-push-notifications/
这是我目前拥有的相关代码: (它的构建没有任何问题)
......
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
......
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
application.registerForRemoteNotifications()
FirebaseApp.configure()
......
return true
}
......
// The callback to handle data message received via FCM for devices running iOS 10 or above.
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
print(#function)
print(remoteMessage.appData)
}
当我尝试对其进行测试时(遵循前面提到的文档中的建议),函数applicationReceivedRemoteMessage()从未被调用,并且我什么也没看到。我想念什么?有什么我应该首先看的吗?
有关信息,我正在使用Xcode版本10.1,iOS 12.1和Swift 4.2。
答案 0 :(得分:1)
在下面检查此代码:
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
setupFireBase(application)
}
func setupFireBase(_ application: UIApplication) {
FirebaseApp.configure()
Messaging.messaging().delegate = self
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()
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
print(messaging)
ClassUserDefault.shared.deviceToken = fcmToken
let dataDict: [String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
connectToFcm()
}
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
}
}
connectToFcm()
}
func connectToFcm() {
InstanceID.instanceID().instanceID { (result, error) in
if let _ = error {
return
} else if let result = result {
print("Remote instance ID token: \(result.token)")
}
}
}
func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken as Data
}
public func application(received remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
completionHandler([UNNotificationPresentationOptions.alert, UNNotificationPresentationOptions.sound, UNNotificationPresentationOptions.badge])
print("Handle push from background or closed")
print("\(notification.request.content.userInfo)")
let _ResponsePush = ClassResponsePush(fromData: notification.request.content.userInfo)
//AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
if notification.request.content.userInfo.isEmpty {
return
} else {
}
print(_ResponsePush)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Handle push from background or closed")
print("\(response.notification.request.content.userInfo)")
let _ResponsePush = ClassResponsePush(fromData: response.notification.request.content.userInfo)
if response.notification.request.content.userInfo.isEmpty { return } else {
handlePush(userInfo: _ResponsePush)
}
print(_ResponsePush)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
var token = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", arguments: [chars[i]])
}
print("Device Token = ", token)
}
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
func handlePush(userInfo: ClassResponsePush) {
}
}
别忘了在Firebase控制台的项目设置的云消息传递中添加.p12文件。
希望它会有所帮助:)
答案 1 :(得分:0)
你好,米歇尔
根据您的参考链接,您似乎错过了这一行
FIRMessaging.messaging().remoteMessageDelegate = self
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 })
// 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()
FIRApp.configure()