Search code examples
iosnativescriptnativescript-angular

Is there a way to catch and cancel the back button event in a NativeScript app on the iOS platform?


I'm working on a NativeScript-Angular app for both Android and iOS but have hit a problem with standard back button navigation. I have resolved the issue for Android, but cannot find a solution for iOS.

The event is causing a problem when going back to a particular page where routing data is expected, resulting in the exception:

"Error: Currently in page back navigation - component should be reattached instead of activated".

My Android solution catches the back button event and cancels it, then calls the router to do the navigation.


 ngOnInit() { 
     if (app.android) {
       app.android.on(app.AndroidApplication.activityBackPressedEvent, 
         (args: any) => this.backEvent(args));
     }
 }

 backEvent(args) {
   args.cancel = true; 
   this.backToRegister(false);
 }

 backToRegister(accepted: boolean){
   this.router.navigate(['/register', 
     this.registerParametersEntered.password, 
     this.registerParametersEntered.confirmPassword, 
     this.registerParametersEntered.code, 
     this.registerParametersEntered.email,
     accepted]);
 }

I want to do something similar with iOS, such as: -

if (app.ios) {
  this.page.on('navigatingFrom', (data) => {
    // TODO cancel the back button event
    this.backToRegister(false);
  })
}

I can't find a way of doing this for iOS - my research is leading me to the conclusion it is not possible to cancel the iOS back button - for example, see here.

Any ideas or alternative suggestions greatly appreciated!


Solution

  • You can't override the back button for iOS. See this SO question. You basically need to create a custom button, you can mimic the appearance of the back button on iOS and add your own event handler. That's how you'd do it in a native iOS app, and how you do it in NativeScript since the native controls are used via NativeScript.

    The actionbar in nativescript can have a custom layout inside or you can just use an action-item and position it on the left for iOS, while also hiding the button on Android if you desire.