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-ios

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 sign in, send or receive messages. The app will abort with an exception until you complete the next step.

Create project

From Firebase console select Add Project.

Call the project FriendlyChat, then click on Create Project.

Connect your iOS app

  1. From the Project Overview screen of your new project, click Add Firebase to your iOS app.
  2. Enter the bundle ID, as "com.google.firebase.codelab.FriendlyChatSwift".
  3. Enter the App Store id as "123456".
  4. Click Register App.

Add GoogleService-Info.plist file to your app

On the second screen click Download GoogleService-Info.plist to 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.

You can now click the "x" in the upper right corner of the popup to close it -- skipping steps 3 and 4 -- as you will perform those steps here.

Import Firebase module

Start by making sure the Firebase module is imported.

AppDelegate.swift, FCViewController.swift

import Firebase

Configure Firebase in AppDelegate

Use the "configure" method in FirebaseApp 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 {
  FirebaseApp.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 {
  FirebaseApp.configure()
  GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.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 = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                      accessToken: authentication.accessToken)
    Auth.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 = Auth.auth().addStateDidChangeListener() { (auth, user) in
      if user != nil {
        MeasurementHelper.sendLoginEvent()
        self.performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
      }
    }
  }

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

Sign Out

Add the Sign out method

FCViewController.swift

  @IBAction func signOut(_ sender: UIButton) {
    let firebaseAuth = Auth.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:cellForRow indexPath:" methods; replace with the code defined below:

FCViewController.swift

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


  func configureDatabase() {
    ref = Database.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] = Auth.auth().currentUser?.displayName
    if let photoURL = Auth.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'

Activate Firebase Storage in dashboard

Go to Firebase console and confirm that Storage is activated with "gs://PROJECTID.apppot.com" domain

If you are seeing the activation window instead, click "GET STARTED" to activate it with default rules.

Configure FirebaseStorage

FCViewController.swift

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

Receive images in existing messages

Add code that downloads images from Firebase Storage.

Modify your FCViewController's "tableView: cellForRowAt indexPath:" 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: DataSnapshot! = 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://") {
        Storage.storage().reference(forURL: imageURL).getData(maxSize: INT64_MAX) {(data, error) in
          if let error = error {
            print("Error downloading: \(error)")
            return
          }
          DispatchQueue.main.async {
            cell.imageView?.image = UIImage.init(data: data!)
            cell.setNeedsLayout()
          }
        }
      } 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 = Auth.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(from: 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 = StorageMetadata()
      metadata.contentType = "image/jpeg"
      self.storageRef.child(imagePath)
        .putData(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 = RemoteConfig.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 = RemoteConfigSettings(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 by trying to send a message longer than 10 characters (extra characters will be truncated.). Update the Remote Config value from 10 to 30, then select Update then Publish Changes. From the navigation bar tap fresh config (in the upper right) 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 = Invites.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 -\(Auth.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 withInvitations: 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 (above SIGN OUT).
  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() {
    Analytics.logEvent(AnalyticsEventLogin, parameters: nil)
  }

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

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

If you want to view this activity in your Firebase 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 Crashlytics allows your application to report when crashes occur and log the events leading up to the crash.

Confirm Firebase Crashlytics dependency

Confirm that pod 'Fabric', '~> 1.7.2' and pod 'Crashlytics', '~> 3.9.3' dependencies exist in your Podfile file.

Add the run script build phase

  1. Open your project in Xcode and select its project file in the Navigator.
  2. Open the Build Phases tab.
  3. Click + Add a new build phase, and select New Run Script Phase.
  4. Add the following line to the Type a script... text box:
"${PODS_ROOT}/Fabric/run"

Initiate crash

FCViewController.swift

  @IBAction func didPressCrash(_ sender: AnyObject) {
    print("Crash button pressed!")
    Crashlytics.sharedInstance().crash()
  }

Test Firebase Crashlytics

  1. Click Build and then run the current scheme in Xcode to build your app on a device or simulator.
  2. Click Stop running the scheme or action in Xcode to close the initial instance of your app. This initial instance includes a debugger that interferes with Crashlytics.
  3. Open your app again from the simulator or device.
  4. Touch Crash to crash the app.
  5. Open your app once more to let the Crashlytics API report the crash. Your crash should show up in the Firebase console within 5 minutes.

Firebase Test Lab lets you test your app on various types of iOS devices across multiple SDK levels and locales. The best part is that all this testing happens automatically in the cloud without you needing to maintain a collection of test devices.

Sign Up for Beta!

Go to http://g.co/firebase/testlabsignup and fill the form with your email and ProjectId

Build XCTests for your app

There are three things you need to do to build iOS tests in a Test Lab-compatible format:

Configure your project's Derived Data location

Xcode places compiled iOS artifacts, including any tests you build, in a Derived Data directory. It is possible to keep the default location for that directory, if you'd like, but it's often helpful to choose a more easily-accessible place for the files, especially if you're going to be running tests with Test Lab often:

  1. Open your project in Xcode.
  2. In the macOS menu bar, select File > Project Settings...
  3. Change the Derived Data dropdown from Default Location to Custom Location.
  4. In the field below the dropdown, select a location for Xcode to output your tests to.

Build generic test files

Test Lab runs instrumentation tests using the XCTest framework. To run your app's XCTests on Test Lab devices, build it for testing on a Generic iOS Device:

  1. From the device dropdown at the top of your Xcode workspace window, select Generic iOS Device.
  2. In the macOS menu bar, select Product > Build For > Testing.

Compress the test files for upload

Finally, package your test for upload to Test Lab by compressing the test files you built into a .zip file:

  1. Open finder, and navigate to the directory you designated for Derived Data output.
  2. Open the folder for your project, then the Build/Products folders inside it.
  3. You should see a folder Debug-iphoneos and PROJECT_NAME_iphoneosDEVELOPMENT_TARGET-arm64.xctestrun. Select them both, then right-click on one of them and select Compress 2 items.

Run your tests

Once you have an XCTest .zip file, you're ready to start testing:

  1. Open Test Lab in the Firebase console.
  2. If it's your first test, click Get Started under iOS. If it isn't, click Run a Test, and select Run an XCTest.
  3. Click Browse, and find the .zip file you created.
  4. Check the box for each device and version you'd like to test on.
  5. Click Start Tests.

Investigate your test results

When the test starts, you're automatically redirected to the test results page. Tests can take a number of minutes to run, depending on the number of different configurations you have selected and the test timeout duration set for your tests. After your tests have run, you can review test results. See Analyzing Firebase Test Lab Results to learn more about how to interpret the test results.

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'

First, let's add a method to display the notifications we're receiving so we'll be able to see them clearly on the UI. Add the following to your AppDelegate:

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)
      }
    }
  }
}

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 {
    FirebaseApp.configure()
    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.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 to handle the incoming notification when the app is in the foreground and show an alert with the notification message.

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)
  }

That's it! Your app is ready to receive messages through FCM.

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.