title: Push notifications in iOS11 (Xcode 9 swift 4)
body: <p>How can I get push notifications on iOS11 in the background? I tried this and never succeeded.</p>
  <p>Why when in the foreground does a notification appear while in the background it doesn't appear? Is there something missing with my source code or settings in the info.plist?</p>
  <pre><code>import UIKit
  import UserNotifications
  import FirebaseCore
  import FirebaseMessaging
  import FirebaseInstanceID
  
  struct DataNotif: Codable {
      var title: String?
      var body: String?
      
      private enum CodingKeys: String, CodingKey {
          case title
          case body
      }
  }
  
  @UIApplicationMain
  class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
      
      var window: UIWindow?
      let gcmMessageIDKey = &quot;gcm.message_id&quot;
      
      static var DEVICE_ID = String()
      var msg_body = &quot;&quot;
      var msg_title = &quot;&quot;
      
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -&gt; Bool {
          
          UIApplication.shared.statusBarStyle = .lightContent
          
          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) { (granted, error) in
                  if (error != nil) {
                      print(&quot;I received the following error: \(error!)&quot;)
                  }else if (granted) {
                      print (&quot;Authorization was granted!&quot;)
                  }else{
                      print (&quot;Authorization was not granted. :(&quot;)
                  }
              }
              
          } else {
              let settings: UIUserNotificationSettings =
                  UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
              application.registerUserNotificationSettings(settings)
          }
          
          application.registerForRemoteNotifications()
          
          return true
      }
      
      func connectToFcm() {
          Messaging.messaging().shouldEstablishDirectChannel = true
      }
   
      func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
          
          if let refreshedToken = InstanceID.instanceID().token() {
              AppDelegate.DEVICE_ID = refreshedToken
              print(&quot;*********&quot;)
              print(&quot;InstanceID token: \(refreshedToken)&quot;)
              print(&quot;*********&quot;)
          }else{
              print(&quot;Can't get token device&quot;)
          }
          
      }
      
      func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
          print(&quot;Failed to register for remote notifications with error: \(error)&quot;)
      }
      
      func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void) {
          
          print(userInfo)
          
          guard let data: [String: Any] = userInfo as? [String: Any] else {
              return
          }
          
          let listData = data[&quot;notification&quot;] as! String
          let jsonData = listData.data(using: .utf8)
          do {
              let decoder = JSONDecoder()
              let dataJson = try decoder.decode(DataNotif.self, from: jsonData!)
              
              msg_body = dataJson.body!
              msg_title = dataJson.title!
              
              createNotification(title: msg_title, body: msg_body)
              
          }catch{
              print(&quot;error&quot;)
          }
          
          completionHandler(.newData)
      }
      
      func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -&gt; Void) {
          
          let notification = response.notification.request.content.body
          
          print(notification)
          
          completionHandler()
          
      }
      
      // messaging
      func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
          
          if let token = InstanceID.instanceID().token() {
              AppDelegate.DEVICE_ID = token
              print(&quot;*********&quot;)
              print(&quot;Token Instance: \(token)&quot;)
              print(&quot;*********&quot;)
          }
   
          connectToFcm()
      }
      
      func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
          
          print(&quot;Received data message: \(remoteMessage.appData)&quot;)
          
          guard let data: [String: Any] = remoteMessage.appData as? [String: Any] else {
              return
          }
          
          print(data)
          
          let listData = data[&quot;notification&quot;] as! String
          let jsonData = listData.data(using: .utf8)
          do {
              let decoder = JSONDecoder()
              let dataJson = try decoder.decode(DataNotif.self, from: jsonData!)
              
              msg_body = dataJson.body!
              msg_title = dataJson.title!
              
              createNotification(title: msg_title, body: msg_body)
              
          }catch{
              print(&quot;error&quot;)
          }
          
      }
      
      func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void) {
          
          completionHandler([.alert, .badge, .sound])
      }
   
      func applicationDidBecomeActive(_ application: UIApplication) {
          UIApplication.shared.applicationIconBadgeNumber = 0
          connectToFcm()
      }
      
      func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void) {
          
          if let vc = window?.rootViewController as? HomeController {
              vc.scheduleNotification()
          }
          
          completionHandler(.newData)
          
      }
      
      func applicationDidEnterBackground(_ application: UIApplication) {
          Messaging.messaging().shouldEstablishDirectChannel = false
          print(&quot;Disconnect FCM&quot;)
      }
   
      func createNotification(title: String, body: String) {
          let content = UNMutableNotificationContent()
          content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
          content.body = NSString.localizedUserNotificationString(forKey: body, arguments: nil)
          content.sound = UNNotificationSound.default()
          content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)
          
          let request = UNNotificationRequest.init(identifier: title, content: content, trigger: nil)
          
          let center = UNUserNotificationCenter.current()
          center.add(request)
      }
      
  }
  </code></pre>
  <p><a href="https://i.stack.imgur.com/yFjKz.png" rel="nofollow noreferrer">This sample post notification in postman</a></p>