title: notification Badge count not set using Apple Push notification - swift - programmatically
body: <p>I'm trying to increment the badge number whenever a new notification is sent to a device using Apple Push Notification system.</p>
  <p>I'm dispatching the notification using a Firebase Cloud Function and this is the code that does that:</p>
  <pre><code>exports.onEmotionCreated = functions.firestore
  .document(&quot;Collection/{doc1}/Collection/{doc2}&quot;)
  .onCreate((snapshot, context) =&gt; {
    const dict = snapshot.data();
    const toUid = dict.toUid;
    const fromUid = dict.fromUid;
    return db.collection(&quot;UserCollection&quot;).doc(fromUid).get().then((snap) =&gt; {
      const fromName = snap.data().name;
      return db.collection(&quot;UserCollection&quot;).doc(toUid).get().then((snapTo) =&gt; {
        const notificationToToken = snapTo.data().notificationToken;
        const notificationContent = {
          notification: {
            title: `${fromName} has sent you a message`,
            body: &quot;Look what's up&quot;,
            icon: &quot;default&quot;,
            sound: &quot;customNotificationSound.wav&quot;,
          },
        };
        return admin.messaging()
            .sendToDevice(notificationToToken, notificationContent)
            .then((result) =&gt;{
              console.log(&quot;write done correctly&quot;);
            });
      });
    });
  });
  </code></pre>
  <p>The notification works fine but apparently on the client side I'm doing something wrong, this is the code I implemented.</p>
  <p>In the main View Controller <code>ViewDidLoad</code> I register the <code>UserDefaults</code> value for key <code>badgeCount</code>:</p>
  <pre><code>var dict = [String: Any]()
      dict.updateValue(0, forKey: &quot;badgeCount&quot;)
      UserDefaults.standard.register(defaults: dict)
  </code></pre>
  <p>Then in app delegate I try to increment the badge using this function:</p>
  <pre><code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void) {
      
      if let userInfoDict = userInfo as? [String : Any]{
          print(&quot;received notification :&quot;)
          print(userInfoDict)
      }
      
      if var badgeCount = UserDefaults.standard.value(forKey: &quot;badgeCount&quot;) as? Int{
          
          badgeCount += 1
          
          UserDefaults.standard.setValue(badgeCount, forKey: &quot;badgeCount&quot;)
          
          UIApplication.shared.applicationIconBadgeNumber = badgeCount
      }
  }
  </code></pre>
  <p>I also gave all the <a href="https://i.stack.imgur.com/wF3Gp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wF3Gp.png" alt="permission" /></a> to the app that apparently allow It to receive notifications when app's in background but it still doesn't get called.</p>