Welcome to the Friendly Chat codelab. In this codelab, you'll learn how to use the Firebase platform to create iOS applications. You will implement a chat client and monitor its performance using Firebase.

This codelab is also available in Objective-C.

What you'll learn

What you'll need

How will you use this tutorial?

Read it through only Read it and complete the exercises

How would rate your experience with building iOS apps?

Novice Intermediate Proficient

Clone the GitHub repository from the command line.

$ git clone https://github.com/firebase/friendlychat

To build the starter app:

  1. In a terminal window, navigate to the ios-starter/swift-starter directory from your sample code download
  2. Run pod update
  3. Open the FriendlyChatSwift.xcworkspace file to open the project in Xcode.
  4. Click the Run button.

You should see the Friendly Chat home screen appear after a few seconds. The UI should appear. However, at this point you cannot send or receive messages.

Create project

From Firebase home page click Console then click on Create New Project.

Call the project FriendlyChat, then click on Create Project.

Connect your iOS app

From the welcome screen of your new project, click Add Firebase to your iOS app.

Enter the bundle ID, e.g. "com.google.firebase.codelab.FriendlyChatSwift".

Enter the Appstore id as "123456".

Click Continue for all the steps of the initial configuration (you don't need to copy the initialization code), then finally click Finish.

Add GoogleService-Info.plist file to your app

After adding the bundle id and App store id and clicking Continue your browser will automatically download a configuration file that contains all the necessary Firebase metadata for your app. Copy that file to your application and add it to the FriendlyChatSwift target.

Import Firebase module

Start by making sure the Firebase module is imported.

AppDelegate.swift

import Firebase

FCViewController.swift

import Firebase

Configure Firebase in AppDelegate

Use the "configure" method in FIRApp inside the application:didFinishLaunchingWithOptions function to configure underlying Firebase services from your .plist file.

AppDelegate.swift

  func application(_ application: UIApplication, didFinishLaunchingWithOptions
      launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  FIRApp.configure()
  GIDSignIn.sharedInstance().delegate = self
  return true
}

Use Rules To Restrict To Authenticated Users

We will now add a rule to require authentication before reading or writing any messages. To do this we add the following rules to our messages data object. From within the Database section of Firebase console select the RULES tab. Then update the rules so they look like this:

{
  "rules": {
        "messages": {
            ".read": "auth != null",
            ".write": "auth != null"
        }
  }
}

For more information on how this works (including documentation on the "auth" variable) see the Firebase security documentation.

Configure Authentication APIs

Before your application can access the Firebase Authentication APIs on behalf of your users, you will have to enable it

  1. Navigate to the Firebase console and select your project
  2. Select Authentication
  3. Select the Sign In Method tab
  4. Toggle the Google switch to enabled (blue)
  5. Press Save on the resulting dialog

If you get errors later in this codelab with the message "CONFIGURATION_NOT_FOUND", come back to this step and double check your work.

Confirm Firebase Auth dependency

Confirm Firebase Auth dependencies exist in the Podfile file.

Podfile

pod 'Firebase/Auth'

Setup your Info.plist for Google Sign In.

You'll need to add a custom URL scheme to your XCode project.

  1. Open your project configuration: double-click the project name in the left tree view. Select your app from the TARGETS section, then select the Info tab, and expand the URL Types section.
  2. Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the GoogleService-Info.plist configuration file, and look for the REVERSED_CLIENT_ID key. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.
  3. When completed, your config should look something similar to the following (but with your application-specific values):

Set clientID for Google Sign In

After Firebase is configured, we can use the clientID to set up the Google Sign In inside the "didFinishLaunchingWithOptions:" method.

AppDelegate.swift

  func application(_ application: UIApplication, didFinishLaunchingWithOptions
      launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  FIRApp.configure()
  GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
  GIDSignIn.sharedInstance().delegate = self
  return true
}

Add the sign in handler

Once the result of the Google Sign-In was successful, use the account to authenticate with Firebase.

AppDelegate.swift

  func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error {
      print("Error \(error)")
      return
    }

    guard let authentication = user.authentication else { return }
    let credential = FIRGoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                      accessToken: authentication.accessToken)
    FIRAuth.auth()?.signIn(with: credential) { (user, error) in
      if let error = error {
        print("Error \(error)")
        return
      }
    }
  }

Automatically sign in the user. Then add a listener to Firebase Auth, to let the user into the app, after successful sign in. And remove the listener on deinit.

SignInViewController.swift

  override func viewDidLoad() {
    super.viewDidLoad()
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().signInSilently()
    handle = FIRAuth.auth()?.addStateDidChangeListener() { (auth, user) in
      if user != nil {
        MeasurementHelper.sendLoginEvent()
        self.performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
      }
    }
  }

  deinit {
    if let handle = handle {
      FIRAuth.auth()?.removeStateDidChangeListener(handle)
    }
  }

Sign Out

Add the Sign out method

FCViewController.swift

  @IBAction func signOut(_ sender: UIButton) {
    let firebaseAuth = FIRAuth.auth()
    do {
      try firebaseAuth?.signOut()
      dismiss(animated: true, completion: nil)
    } catch let signOutError as NSError {
      print ("Error signing out: \(signOutError.localizedDescription)")
    }
  }

Test Reading Messages as Signed In User

  1. Click the Run button.
  2. You should be immediately sent to the sign-in screen. Tap the Google Sign-In button.
  3. You should then be sent to the messaging screen if everything worked well.

Import Messages

In your project in Firebase console select the Database item on the left navigation bar. In the overflow menu of the Database select Import JSON. Browse to the initial_messages.json file in the friendlychat directory, select it then click the Import button. This will replace any data currently in your database. You could also edit the database directly, using the green + and red x to add and remove items.

After importing your database should look like this:

Confirm Firebase Database Dependency

In the dependencies block of the Podfile file, confirm that Firebase/Database is included.

Podfile

pod 'Firebase/Database'

Synchronize Existing Messages

Add code that synchronizes newly added messages to the app UI.

The code you add in this section will:

Modify your FCViewController's "deinit", "configureDatabase", and "tableView" methods; replace with the code defined below:

FCViewController.swift

  deinit {
    if let refHandle = _refHandle {
      self.ref.child("messages").removeObserver(withHandle: _refHandle)
    }
  }


  func configureDatabase() {
    ref = FIRDatabase.database().reference()
    // Listen for new messages in the Firebase database
    _refHandle = self.ref.child("messages").observe(.childAdded, with: { [weak self] (snapshot) -> Void in
      guard let strongSelf = self else { return }
      strongSelf.messages.append(snapshot)
      strongSelf.clientTable.insertRows(at: [IndexPath(row: strongSelf.messages.count-1, section: 0)], with: .automatic)
    })
  }


  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Dequeue cell
    let cell = self.clientTable.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath)
    // Unpack message from Firebase DataSnapshot
    let messageSnapshot = self.messages[indexPath.row]
    guard let message = messageSnapshot.value as? [String: String] else { return cell }
    let name = message[Constants.MessageFields.name] ?? ""
    let text = message[Constants.MessageFields.text] ?? ""
    cell.textLabel?.text = name + ": " + text
    cell.imageView?.image = UIImage(named: "ic_account_circle")
    if let photoURL = message[Constants.MessageFields.photoURL], let URL = URL(string: photoURL),
        let data = try? Data(contentsOf: URL) {
      cell.imageView?.image = UIImage(data: data)
    }
    return cell
  }

Test Message Sync

  1. Click the Run button.
  2. Click the Sign in to get started button to go to the messages window.
  3. Add new messages directly in Firebase console by clicking on the green + symbol next to the "messages" entry and adding an object like the following:
  4. Confirm that they show up in the Friendly-Chat UI.

Implement Send Message

Push values to the database. When you use the push method to add data to Firebase Realtime Database, an automatic ID will be added. These auto generated IDs are sequential, which ensures that new messages will be added in the correct order.

Modify your FCViewController's "sendMessage" method; replace with the code defined below:

FCViewController.swift

  func sendMessage(withData data: [String: String]) {
    var mdata = data
    mdata[Constants.MessageFields.name] = FIRAuth.auth()?.currentUser?.displayName
    if let photoURL = FIRAuth.auth()?.currentUser?.photoURL {
      mdata[Constants.MessageFields.photoURL] = photoURL.absoluteString
    }

    // Push data to Firebase Database
    self.ref.child("messages").childByAutoId().setValue(mdata)
  }

Test Sending Messages

  1. Click the Run button.
  2. Click Sign In to go to the messages window.
  3. Type out a message and hit send. The new message should be visible in the app UI and in the Firebase console.

Confirm Firebase Storage Dependency

In the dependencies block of the Podfile, confirm Firebase/Storage is included.

Podfile

pod 'Firebase/Storage'

Configure FirebaseStorage

FCViewController.swift

  func configureStorage() {
    storageRef = FIRStorage.storage().reference()
  }

Receive images in existing messages

Add code that downloads images from Firebase Storage.

Modify your FCViewController's "tableView" method; replace with the code defined below:

FCViewController.swift

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Dequeue cell
    let cell = self.clientTable .dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath)
    // Unpack message from Firebase DataSnapshot
    let messageSnapshot: FIRDataSnapshot! = self.messages[indexPath.row]
    guard let message = messageSnapshot.value as? [String:String] else { return cell }
    let name = message[Constants.MessageFields.name] ?? ""
    if let imageURL = message[Constants.MessageFields.imageURL] {
      if imageURL.hasPrefix("gs://") {
        FIRStorage.storage().reference(forURL: imageURL).data(withMaxSize: INT64_MAX) {(data, error) in
          if let error = error {
            print("Error downloading: \(error)")
            return
          }
          cell.imageView?.image = UIImage.init(data: data!)
          tableView.reloadData()
        }
      } else if let URL = URL(string: imageURL), let data = try? Data(contentsOf: URL) {
        cell.imageView?.image = UIImage.init(data: data)
      }
      cell.textLabel?.text = "sent by: \(name)"
    } else {
      let text = message[Constants.MessageFields.text] ?? ""
      cell.textLabel?.text = name + ": " + text
      cell.imageView?.image = UIImage(named: "ic_account_circle")
      if let photoURL = message[Constants.MessageFields.photoURL], let URL = URL(string: photoURL),
          let data = try? Data(contentsOf: URL) {
        cell.imageView?.image = UIImage(data: data)
      }
    }
    return cell
  }

Implement Store and Send Images

Upload an image from the user, then sync this image's storage URL to database so this image is sent inside the message.

Modify your FCViewController's "imagePickerController didFinishPickingMediaWithInfo" method; replace with the code defined below:

FCViewController.swift

  func imagePickerController(_ picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : Any]) {
      picker.dismiss(animated: true, completion:nil)
    guard let uid = FIRAuth.auth()?.currentUser?.uid else { return }

    // if it's a photo from the library, not an image from the camera
    if #available(iOS 8.0, *), let referenceURL = info[UIImagePickerControllerReferenceURL] as? URL {
      let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
      let asset = assets.firstObject
      asset?.requestContentEditingInput(with: nil, completionHandler: { [weak self] (contentEditingInput, info) in
        let imageFile = contentEditingInput?.fullSizeImageURL
        let filePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\((referenceURL as AnyObject).lastPathComponent!)"
        guard let strongSelf = self else { return }
        strongSelf.storageRef.child(filePath)
          .putFile(imageFile!, metadata: nil) { (metadata, error) in
            if let error = error {
              let nsError = error as NSError
              print("Error uploading: \(nsError.localizedDescription)")
              return
            }
            strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
          }
      })
    } else {
      guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
      let imageData = UIImageJPEGRepresentation(image, 0.8)
      let imagePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
      let metadata = FIRStorageMetadata()
      metadata.contentType = "image/jpeg"
      self.storageRef.child(imagePath)
        .put(imageData!, metadata: metadata) { [weak self] (metadata, error) in
          if let error = error {
            print("Error uploading: \(error)")
            return
          }
          guard let strongSelf = self else { return }
          strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
      }
    }
  }

Test Sending and Receiving Image Messages

  1. Click the Run button.
  2. Click Sign In to go to the messages window.
  3. Click "add a photo" icon to pick a photo. The new message with the photo should be visible in the app UI and in the Firebase console.

Firebase Remote Config allows you to remotely configure your active clients. FriendlyChat messages are restricted to a maximum length. While this length can be defined directly in the client, defining this maximum length with Firebase Remote Config allows an update to the maximum length to be applied to active clients.

Add Config Rules in Firebase console

In Firebase console, select the "Remote Config" panel and click "Add your first parameter". Set the parameter key to friendly_msg_length and the parameter value to 10. Select Publish Changes to apply the updates.

Confirm Firebase RemoteConfig dependency

Confirm the pod 'Firebase/RemoteConfig' dependency exists in your Podfile file.

Configure Firebase Remote Config

FCViewController.swift

  func configureRemoteConfig() {
    remoteConfig = FIRRemoteConfig.remoteConfig()
    // Create Remote Config Setting to enable developer mode.
    // Fetching configs from the server is normally limited to 5 requests per hour.
    // Enabling developer mode allows many more requests to be made per hour, so developers
    // can test different config values during development.
    let remoteConfigSettings = FIRRemoteConfigSettings(developerModeEnabled: true)
    remoteConfig.configSettings = remoteConfigSettings!
  }

Request and Use Config

Create a fetch request for config and add a completion handler to pick up and use the config parameters.

FCViewController.swift

  func fetchConfig() {
    var expirationDuration: TimeInterval = 3600
    // If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from
    // the server.
    if self.remoteConfig.configSettings.isDeveloperModeEnabled {
      expirationDuration = 0
    }

    // cacheExpirationSeconds is set to cacheExpiration here, indicating that any previously
    // fetched and cached config would be considered expired because it would have been fetched
    // more than cacheExpiration seconds ago. Thus the next fetch would go to the server unless
    // throttling is in progress. The default expiration duration is 43200 (12 hours).
    remoteConfig.fetch(withExpirationDuration: expirationDuration) { [weak self] (status, error) in
      if status == .success {
        print("Config fetched!")
        guard let strongSelf = self else { return }
        strongSelf.remoteConfig.activateFetched()
        let friendlyMsgLength = strongSelf.remoteConfig["friendly_msg_length"]
        if friendlyMsgLength.source != .static {
          strongSelf.msglength = friendlyMsgLength.numberValue!
          print("Friendly msg length config: \(strongSelf.msglength)")
        }
      } else {
        print("Config not fetched")
        if let error = error {
          print("Error \(error)")
        }
      }
    }
  }

Test Remote Config

  1. Click the Run button.
  2. Check that the Friendly Message character limit has been set to 10. Update the Remote Config value from 10 to 30, then publish. From the navigation bar tap fresh config and confirm that the Friendly Message character limit is now 30.

Firebase App Invites provide a simple way for your users to share your application with their friends through Email or SMS.

Confirm AppInvite dependency

Confirm the pod 'Firebase/Invites' dependency exists in your Podfile:

Podfile

pod 'Firebase/Invites'

Present invite dialog when invite button is clicked:

FCViewController.swift

  @IBAction func inviteTapped(_ sender: AnyObject) {
    if let invite = FIRInvites.inviteDialog() {
      invite.setInviteDelegate(self)

      // NOTE: You must have the App Store ID set in your developer console project
      // in order for invitations to successfully be sent.

      // A message hint for the dialog. Note this manifests differently depending on the
      // received invitation type. For example, in an email invite this appears as the subject.
      invite.setMessage("Try this out!\n -\(FIRAuth.auth()?.currentUser?.displayName ?? "")")
      // Title for the dialog, this is what the user sees before sending the invites.
      invite.setTitle("FriendlyChat")
      invite.setDeepLink("app_url")
      invite.setCallToActionText("Install!")
      invite.setCustomImage("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")
      invite.open()
    }
  }

Add the inviteFinished handler to print out the result.

FCViewController.swift

func inviteFinished(withInvitations invitationIds: [Any], error: Error?) {
  if let error = error {
    print("Failed: \(error.localizedDescription)")
  } else {
    print("Invitations sent")
  }
}

Test App Invite

  1. Click the Run button.
  2. Click the "Invite" button.
  3. You should see the App Invites interface which will allow you to select Email and SMS contacts and send a custom invitation. You must have control of the receiving account to view the invitation once sent.
  4. Tap send and verify that the invitation is sent to the selected contact.
  5. Verify that selected contact is taken to app install screen from invite.

You now know how to enable invites. Congrats!

Firebase Analytics provides a way for you to understand the way users move through your application, where they succeed and where they get stuck and turn back. It can also be used to understand the most used parts of your application.

Initialize Measurement

Add measurement helper methods.

MeasurementHelper.swift

  static func sendLoginEvent() {
    FIRAnalytics.logEvent(withName: kFIREventLogin, parameters: nil)
  }

  static func sendLogoutEvent() {
    FIRAnalytics.logEvent(withName: "logout", parameters: nil)
  }

  static func sendMessageEvent() {
    FIRAnalytics.logEvent(withName: "message", parameters: nil)
  }

If you want to view this activity in your console, select Product ... Scheme... Edit Scheme in Xcode. In the Arguments Passed on Launch section, click the + to add a new argument and add add `-FIRAnalyticsDebugEnabled` as the new argument.

AdMob gives you a way to easily monetize the application, you simply add the AdView placeholder and Google handles the ad delivery for you.

Confirm the AdMob dependency

Confirm the pod 'Firebase/AdMob' dependency exists in your Podfile file.

Podfile

pod 'Firebase/AdMob'

Load Ad request

FCViewController.swift

  func loadAd() {
    self.banner.adUnitID = kBannerAdUnitID
    self.banner.rootViewController = self
    self.banner.load(GADRequest())
  }

Test AdMob

  1. Click the Run button.
  2. Verify that the Test Ad shows at the bottom of the screen.

Firebase Crash allows your application to report when crashes occur and log the events leading up to the crash.

Confirm Firebase Crash dependency

Confirm the pod 'Firebase/Crash' dependency exists in your Podfile file.

FCViewController.swift

  func logViewLoaded() {
    FIRCrashMessage("View loaded")
  }

Initiate crash

FCViewController.swift

  @IBAction func didPressCrash(_ sender: AnyObject) {
    FIRCrashMessage("Cause Crash button clicked")
    fatalError()
  }

Test Firebase Crash

  1. Click the Run button.
  2. Stop Xcode
  3. Run the app again without Xcode attached from the simulator.
  4. Click the "Crash" button.
  5. Verify that your app is crashed.
  6. Click the Run button again to run your app in Xcode
  7. After a moment, you should see the message "Firebase Crash Reporting: Crash successfully uploaded" in the console
  8. After a minute or two, visit the Crash section of the Firebase console. You should see your crash being logged
  9. Note that we did not do the work to upload the symbols file in this codelab. In a real situation, you would have a much more readable stack trace to help you find the error.

You have used Firebase to easily build a real-time chat application.

What we've covered

Optional Steps

Learn More

You can use Firebase Cloud Messaging (FCM) to send notifications to users of your app. In this section we will configure the application to receive reengagement notifications which you can send from Firebase console.

Add FCM dependency

The Firebase/Messaging dependency provides the ability to send and receive FCM messages. Confirm the pod 'Firebase/Messaging' dependency exists in your Podfile file.

Podfile

pod 'Firebase/Messaging'

Register for remote notifications

Implement UNUserNotificationCenterDelegate after the implementation of "AppDelegate" class (append to the end of the file) to receive display notification via APNS for devices running iOS 10 and above.

AppDelegate.swift

import UserNotifications

@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
    showAlert(withUserInfo: 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
    showAlert(withUserInfo: userInfo)
    
    completionHandler()
  }
}

Register your app for remote notifications inside the "application:didFinishLaunchingWithOptions:" function

AppDelegate.swift

  func application(_ application: UIApplication, didFinishLaunchingWithOptions
    launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


    FIRApp.configure()
    GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self

    // 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.
    if #available(iOS 10.0, *) {
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
      options: authOptions) {_,_ in }
      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.current().delegate = self
    } else {
      let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
      application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    return true
  }

At this point, you'll receive notifications when the app is in the background. Add notification handlers and alert function, to handle the incoming notification when the app is in foreground and show an alert with the message of the notification.

AppDelegate.swift

  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.

    showAlert(withUserInfo: 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.

    showAlert(withUserInfo: userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
  }

  func showAlert(withUserInfo userInfo: [AnyHashable : Any]) {
    let apsKey = "aps"
    let gcmMessage = "alert"
    let gcmLabel = "google.c.a.c_l"

    if let aps = userInfo[apsKey] as? NSDictionary {
      if let message = aps[gcmMessage] as? String {
        DispatchQueue.main.async {
          let alert = UIAlertController(title: userInfo[gcmLabel] as? String ?? "",
                                        message: message, preferredStyle: .alert)
          let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
          alert.addAction(dismissAction)
          self.window?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)
        }
      }
    }
  }

That's it! FCM is all ready to receive messages.

Test Background Notifications

  1. Run the updated application.
  2. Hit the device's home button (or otherwise send the app to the background).
  3. Use the Composer in the Firebase console to send notifications.
  1. In Firebase console select Notifications from the left navigation bar.
  2. Select Send Your First Message.
  3. Set Message Text to "Friendly Chat?".
  4. Select the app we connected earlier as the App target.
  5. Click Send Message
  1. Confirm that message is received and notification is displayed on the device. The user should receive a notification that takes them back to the application when tapped. And the application should show an alert: "Friendly Chat?"

Hooray! You can re-engage your users easily with FCM. See the documentation for more on FCM.