App crash on startup when enable push notifications

Hello :slight_smile:
I try to implement push notifications to my app but it won’t work.

I started with the android version, and that wasn’t difficult, it work’s fine.
The build for ios also generated, but when I start the app, it crash imidiatly.
Anyone have an idea what’s wrong? Maybe anyone can share an working config for push notifications.

App facts:
Build: via Appflow

Files structur:
app

Podfile

platform :ios, '11.0'
use_frameworks!

# workaround to avoid Xcode caching of Pods that requires
# Product -> Clean Build Folder after new Cordova plugins installed
# Requires CocoaPods 1.6 or newer
install! 'cocoapods', :disable_input_output_paths => true

def capacitor_pods
  # Automatic Capacitor Pod dependencies, do not delete
  pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
  pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
  pod 'CordovaPlugins', :path => '../capacitor-cordova-ios-plugins'
  # Do not delete
end

target 'App' do
  capacitor_pods
  # Add your Pods here
  pod 'FirebaseCore'
  pod 'Firebase/Messaging'
end

AppDelegate.swift

import UIKit
import Capacitor
import FirebaseCore
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?


  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    return true
  }

  func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  }

  func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  }

  func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
  }

  func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  }

  func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  }

  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    // Called when the app was launched with a url. Feel free to add additional processing here,
    // but if you want the App API to support tracking app url opens, make sure to keep this call
    return CAPBridge.handleOpenUrl(url, options)
  }
  
  func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    // Called when the app was launched with an activity, including Universal Links.
    // Feel free to add additional processing here, but if you want the App API to support
    // tracking app url opens, make sure to keep this call
    return CAPBridge.handleContinueActivity(userActivity, restorationHandler)
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    let statusBarRect = UIApplication.shared.statusBarFrame
    guard let touchPoint = event?.allTouches?.first?.location(in: self.window) else { return }

    if statusBarRect.contains(touchPoint) {
      NotificationCenter.default.post(CAPBridge.statusBarTappedNotification)
    }
  }

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
    InstanceID.instanceID().instanceID { (result, error) in
        if let error = error {
            NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidFailToRegisterForRemoteNotificationsWithError.name()), object: error)
        } else if let result = result {
            NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidRegisterForRemoteNotificationsWithDeviceToken.name()), object: result.token)
        }
    }
  }

  func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidFailToRegisterForRemoteNotificationsWithError.name()), object: error)
  }
}

Have you been able to figure this out? I’m having the same issue. Android worked fine on a device emulator, but wont work when I create a build for IOS. Instantly crashes when opening. Doesn’t even make it to the splash screen. Spent a whole day trying to figure it out and trying to work it out with support but really got no where. I’m currently still working with ionic support to try and get this worked out.

It is exactly the same with my app :frowning:

I’m working on the problem at the moment, i hope i can figure out a solution in the next few hours.

Hi, basic question but, are you sure you implement correct keys in Info.plist ?
Also, which version of firebase are you using ? Before v7, if I’m right the firebase packages were using WebView and after, WkWebView that is now mandatory on iOS systems.

When launching with Xcode, does the console returns you something ?

You can also try to enable push notifications in a page instead of the launching part, just to see if it works.

Hi, do I need to add some keys in the Info.plist? Never saw anything in the docs.

That's my Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>de-AT</string>
    <key>CFBundleDisplayName</key>
    <string>myApp</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>3.0.0</string>
    <key>CFBundleURLTypes</key>
    <array>
      <dict>
        <key>CFBundleURLName</key>
        <string>com.getcapacitor.capacitor</string>
        <key>CFBundleURLSchemes</key>
        <array>
          <string>capacitor</string>
        </array>
      </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>6</string>
    <key>LSRequiresIPhoneOS</key>
    <true />
    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true />
    </dict>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Allow Geolocation?</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>To Pick Photos from Library</string>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
      <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
      <string>UIInterfaceOrientationPortrait</string>
      <string>UIInterfaceOrientationLandscapeLeft</string>
      <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
      <string>UIInterfaceOrientationPortrait</string>
      <string>UIInterfaceOrientationPortraitUpsideDown</string>
      <string>UIInterfaceOrientationLandscapeLeft</string>
      <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true />
    <key>UIStatusBarStyle</key>
    <string>UIStatusBarStyleDefault</string>
    <key>IonMaxVersions</key>
    <string>2</string>
    <key>IonMinBackgroundDuration</key>
    <string>30</string>
    <key>IonApi</key>
    <string>https://api.ionicjs.com</string>
    <key>IonAppId</key>
    <string>1234567890</string>
    <key>IonChannelName</key>
    <string>Development</string>
    <key>IonUpdateMethod</key>
    <string>background</string>
  </dict>
</plist>

When launching with Xcode, does the console returns you something ?

I am using Appflow to build the app.

You can also try to enable push notifications in a page instead of the launching part, just to see if it works.

I am not sure what you mean?

Which dependency are you using to implement Push Notifications ?

Can you give the code of this part/ts file ?

I only have dependencies to capacitor. The android build works without any problems.

import {Injectable} from '@angular/core';
import {Plugins, PushNotification, PushNotificationActionPerformed, PushNotificationToken} from '@capacitor/core';

@Injectable({
  providedIn: 'root'
})
export class FirebaseService {

  public async init() {
    await this.initPushNotification();
  }

  private async initPushNotification() {
    const PushNotifications = Plugins.PushNotifications;

    await PushNotifications.requestPermission().then(async premissions => {
      if (premissions?.granted) {
        PushNotifications.addListener('registration', ((response: PushNotificationToken) => {
            alert('Copied Push token to Clipboard: ' + response.value);
          })
        );

        PushNotifications.addListener('pushNotificationReceived', ((data: PushNotification) => {
          alert('Push Notification:\n' + JSON.stringify(data, null, 2));
        }));
        PushNotifications.addListener('pushNotificationActionPerformed', ((data: PushNotificationActionPerformed) => {
          alert('Push ActionPerformed:\n' + JSON.stringify(data, null, 2));
        }));

        await PushNotifications.register();
      } else {
        alert('no push Permissions');
      }
    });
  }
}

I was able to solve the problem :slight_smile:

I opened the project with xcode and added GoogleService-Info.plist to the App workspace.
Now everything works fine.

2 Likes