Create a Firebase project in the Firebase console(https://console.firebase.google.com/?pli=1), if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
AppDelegate.swift
Add the pods that you want to install. You can include a Pod in your
Podfile like this:
$ pod 'Firebase/Core'
$ pod 'Firebase/Messaging'
$ pod install
Send a Notification to an iOS Device
With Firebase Notifications, you can target notifications to a single, specific device. You need access to the registration token for the app instance on that device, to provide the token when composing and sending the notification in the Notifications console.
Add Firebase to your iOS project
This section covers tasks you may have completed if you have already enabled other Firebase features for your app. For Notifications specifically, you'll need to upload your APNs certificate(https://firebase.google.com/docs/notifications/ios/console-device#upload_your_apns_certificate) andregister for remote notifications(https://firebase.google.com/docs/notifications/ios/console-device#register_for_remote_notifications).
Prerequisites
Before you begin, you need a few things set up in your environment:
- Xcode 7.0 or later
- An Xcode project targeting iOS 7 or above
- The bundle identifier of your app
- CocoaPods 1.0.0 or later
- For Cloud Messaging:
- A physical iOS device
- APNs certificate with Push Notifications enabled
- In Xcode, enable Push Notifications in App > Capabilities
If you don't have an Xcode project already, you can download one of our quickstart samples if you just want to try a Firebase feature. If you're using a quickstart, remember to get the bundle identifier from the project settings, you'll need it for the next step.
Add Firebase to your app
It's time to add Firebase to your app. To do this you'll need a Firebase project and a Firebase configuration file for your app.
- Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
- Click Add Firebase to your iOS app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
- When prompted, enter your app's bundle ID. It's important to enter the bundle ID your app is using; this can only be set when you add an app to your Firebase project.
- At the end, you'll download a
GoogleService-Info.plistfile. You can download this fileagain at any time. - If you haven't done so already, copy this into your Xcode project root.
Add the SDK
If you are setting up a new project, you need to install the SDK. You may have already completed this as part of creating a Firebase project.
We recommend using CocoaPods to install the libraries. You can install Cocoapods by following theinstallation instructions. If you'd rather not use CocoaPods, you can integrate the SDK frameworks directly by following the instructions below.
If you are planning to download and run one of the quickstart samples the Xcode project and Podfile are already present. If you would like to integrate the Firebase libraries into one of your own projects, you will need to install the pods for the libraries that you want to use.
- If you don't have an Xcode project yet, create one now.
- Create a
Podfileif you don't have one:$ cd your-project directory $ pod init - Add the pods that you want to install. You can include a Pod in your
Podfilelike this:pod 'Firebase/Core' pod 'Firebase/Messaging'This will add the prerequisite libraries needed to get Firebase up and running in your iOS app, along with Firebase Analytics. A list of currently available pods and subspecs is provided below. These are linked in feature specific setup guides as well. - Install the pods and open the .xcworkspace file to see the project in Xcode.
$ pod install $ open your-project.xcworkspace
Upload your APNs certificate
Upload your APNs certificate to Firebase. If you don't already have an APNs certificate, see Provisioning APNs SSL Certificates.(https://firebase.google.com/docs/cloud-messaging/ios/certs)
- Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.
- Select the Upload Certificate button for your development certificate, your production certificate, or both. At least one is required.
- For each certificate, select the .p12 file, and provide the password, if any. Make sure the bundle ID for this certificate matches the bundle ID of your app. Select Save.
AppDelegate.swift
| import UserNotifications | |
| import UIKit | |
| import Firebase | |
| import FirebaseInstanceID | |
| import FirebaseMessaging | |
| @UIApplicationMain | |
| class AppDelegate: UIResponder, UIApplicationDelegate { | |
| var window: UIWindow? | |
| let gcmMessageIDKey = "gcm.message_id" | |
| func application(_ application: UIApplication, | |
| didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { | |
| // Register for remote notifications. This shows a permission dialog on first run, to | |
| // show the dialog at a more appropriate time move this registration accordingly. | |
| // [START register_for_notifications] | |
| 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() | |
| // [END register_for_notifications] | |
| FIRApp.configure() | |
| // Add observer for InstanceID token refresh callback. | |
| NotificationCenter.default.addObserver(self, | |
| selector: #selector(self.tokenRefreshNotification), | |
| name: .firInstanceIDTokenRefresh, | |
| object: nil) | |
| return true | |
| } | |
| // [START receive_message] | |
| func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { | |
| // If you are receiving a notification message while your app is in the background, | |
| // this callback will not be fired till the user taps on the notification launching the application. | |
| // TODO: Handle data of notification | |
| // Print message ID. | |
| if let messageID = userInfo[gcmMessageIDKey] { | |
| print("Message ID: \(messageID)") | |
| } | |
| // Print full message. | |
| print(userInfo) | |
| } | |
| func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], | |
| fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { | |
| // If you are receiving a notification message while your app is in the background, | |
| // this callback will not be fired till the user taps on the notification launching the application. | |
| // TODO: Handle data of notification | |
| // Print message ID. | |
| if let messageID = userInfo[gcmMessageIDKey] { | |
| print("Message ID: \(messageID)") | |
| } | |
| // Print full message. | |
| print(userInfo) | |
| completionHandler(UIBackgroundFetchResult.newData) | |
| } | |
| // [END receive_message] | |
| // [START refresh_token] | |
| func tokenRefreshNotification(_ notification: Notification) { | |
| if let refreshedToken = FIRInstanceID.instanceID().token() { | |
| print("InstanceID token: \(refreshedToken)") | |
| } | |
| // Connect to FCM since connection may have failed when attempted before having a token. | |
| connectToFcm() | |
| } | |
| // [END refresh_token] | |
| // [START connect_to_fcm] | |
| func connectToFcm() { | |
| // Won't connect since there is no token | |
| guard FIRInstanceID.instanceID().token() != nil else { | |
| return; | |
| } | |
| // Disconnect previous FCM connection if it exists. | |
| FIRMessaging.messaging().disconnect() | |
| FIRMessaging.messaging().connect { (error) in | |
| if error != nil { | |
| print("Unable to connect with FCM. \(error)") | |
| } else { | |
| print("Connected to FCM.") | |
| } | |
| } | |
| } | |
| // [END connect_to_fcm] | |
| func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { | |
| print("Unable to register for remote notifications: \(error.localizedDescription)") | |
| } | |
| // This function is added here only for debugging purposes, and can be removed if swizzling is enabled. | |
| // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to | |
| // the InstanceID token. | |
| func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { | |
| print("APNs token retrieved: \(deviceToken)") | |
| // With swizzling disabled you must set the APNs token here. | |
| // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox) | |
| } | |
| // [START connect_on_active] | |
| func applicationDidBecomeActive(_ application: UIApplication) { | |
| connectToFcm() | |
| } | |
| // [END connect_on_active] | |
| // [START disconnect_from_fcm] | |
| func applicationDidEnterBackground(_ application: UIApplication) { | |
| FIRMessaging.messaging().disconnect() | |
| print("Disconnected from FCM.") | |
| } | |
| // [END disconnect_from_fcm] | |
| } | |
| // [START ios_10_message_handling] | |
| @available(iOS 10, *) | |
| extension AppDelegate : UNUserNotificationCenterDelegate { | |
| // Receive displayed notifications for iOS 10 devices. | |
| func userNotificationCenter(_ center: UNUserNotificationCenter, | |
| willPresent notification: UNNotification, | |
| withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { | |
| let userInfo = notification.request.content.userInfo | |
| // Print message ID. | |
| if let messageID = userInfo[gcmMessageIDKey] { | |
| print("Message ID: \(messageID)") | |
| } | |
| // Print full message. | |
| print(userInfo) | |
| // Change this to your preferred presentation option | |
| completionHandler([]) | |
| } | |
| func userNotificationCenter(_ center: UNUserNotificationCenter, | |
| didReceive response: UNNotificationResponse, | |
| withCompletionHandler completionHandler: @escaping () -> Void) { | |
| let userInfo = response.notification.request.content.userInfo | |
| // Print message ID. | |
| if let messageID = userInfo[gcmMessageIDKey] { | |
| print("Message ID: \(messageID)") | |
| } | |
| // Print full message. | |
| print(userInfo) | |
| completionHandler() | |
| } | |
| } | |
| // [END ios_10_message_handling] | |
| // [START ios_10_data_message_handling] | |
| extension AppDelegate : FIRMessagingDelegate { | |
| // Receive data message on iOS 10 devices while app is in the foreground. | |
| func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { | |
| print(remoteMessage.appData) | |
| } | |
| } | |
| // [END ios_10_data_message_handling] |
No comments:
Post a Comment