I'm trying to execute a method when the user leaves the app. I tried everything:
ionViewWillUnload() {
console.log("Wlill unload");
this.leaveRoom();
}
onDestroy() {
console.log("DESTROY");
this.leaveRoom();
}
ionViewWillLeave() {
this.leaveRoom();
}
Unfortunetly they are not executed when user closes the app or when the user refresh the page.
Any idea?
Import Platform:
import { Platform } from 'ionic-angular';
Add Platform to the constuctor:
constructor(public navCtrl: NavController, platform: Platform)
subscribe to the platform pause and resume:
platform.ready().then(() => {
this.platform.pause.subscribe(() => {
console.log('[INFO] App paused');
});
this.platform.resume.subscribe(() => {
console.log('[INFO] App resumed');
});
});
I think what are you looking for can be found here:
http://cordova.apache.org/docs/en/6.x/cordova/events/events.html#endcallbutton
Specifically this event:
function onEndCallKeyDown() {
// Handle the end call button
}
In order to make the event work you have to declare this listener first:
document.addEventListener("endcallbutton", onEndCallKeyDown, false);
onPause Event:
document.addEventListener("pause", onPause, false);
function onPause() {
// Handle the pause event
}
onResume event
document.addEventListener("resume", onResume, false);
function onResume() {
// Handle the resume event
}
Hope it helps!
Related
I have implemented one application in which the page will redirect to a page showing “no network” when the user gone offline. I have successfully implemented that. App navigates to the below screen when there is no network.In the below scenario the logic fails,’
Application fails to redirect to the " no network page " when the user opens the application for the first time or after kill during offline. In this case application launches the default root page say LoginPage.
Please find the logic below.
NetworkCheckProvider.ts
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network';
import { Events } from "ionic-angular";
export enum ConnectionStatusEnum {
Online,
Offline
}
#Injectable()
export class NetworkCheckProvider {
private previousStatus;
constructor(private eventCtrl: Events,
private netWork:Network) {
this.previousStatus = ConnectionStatusEnum.Online;
}
public initializeNetworkEvents(): void {
this.netWork.onDisconnect().subscribe(() => {
if (this.previousStatus === ConnectionStatusEnum.Online) {
this.eventCtrl.publish('network:offline');
}
this.previousStatus = ConnectionStatusEnum.Offline;
});
this.netWork.onConnect().subscribe(() => {
if (this.previousStatus === ConnectionStatusEnum.Offline) {
this.eventCtrl.publish('network:online');
}
this.previousStatus = ConnectionStatusEnum.Online;
});
}
}
app.component.ts
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.networkCheck();
this.netWorkCheck.initializeNetworkEvents();
}
networkCheck() {
this.events.subscribe('network:online', () => {
this.generic.showToast("Network Available");
console.log('network connected!');
});
this.events.subscribe('network:offline', () => {
debugger;
if(this.nav.getActive().name!='NoInternetPage' || this.nav.getActive().name==null)
this.nav.push('NoInternetPage');
});
}
}
Please correct me if there is any mistake in my code. Also is there is any way to disable all click events during offline?
Thanks and Regards
Anand Raj
I am trying to use alertify confirmation box when someone tries to navigate from the page. But in the willTransition action of the route, alertify is very asynchronous, and ember doesn't wait for the confirmation. No matter what you click, the page is already navigated.
willTransition(transition) {
alertify.confirm('Confirm', 'Are you sure you want to navigate?', function(e) {
if(e) {
return true;
} else {
transition.abort();
}
});
}
Please help me with this!!
You can abort and retry transitions. You have to abort the transition before showing the confirmation dialog. After confirming your dialog you can retry the transition and prevent your code from showing your confirmation dialog again. So the following should work (not tested):
export default Ember.Route.extend({
// ...
showConfirmation: true,
actions: {
willTransition(transition) {
if(!this.get('showConfirmation')) {
this.set('showConfirmation', true);
return true;
}
// Abort the transition for now
transition.abort();
// Now show a confirm box with alertify.
// According to the docs, only the following
// is allowed: http://alertifyjs.com/confirm.html
alertify.confirm('Are you sure you want to navigate?', () => {
// According to the documentation of alertify,
// this code is only run when you confirm your box.
this.set('showConfirmation', false);
transition.retry();
});
}
}
}
I use inappbrowser plugin in ionic 2 application like this :
import {InAppBrowser} from 'ionic-native';
and use it like this :
launch(url){
this.browser = new InAppBrowser( url, "_blank", "EnableViewPortScale=yes,closebuttoncaption=Done" );
this.browser.on("exit")
.subscribe(
() => {
this.close_event=true;
},
err => {
console.log("InAppBrowser Loadstop Event Error: " + err);
});
}
and in html :
<button ion-button icon-right color="danger" (click)="launch('https://www.example.com')">launch
<ion-icon name="refresh"></ion-icon>
when click on launch button for first time and after close browser, exit event not fire but when for second time click on launch button and after close browser exit event is fire
Perhaps the first time you click on Launch button, the device platform is not ready yet?
Try to put the calls to any InAppBrowser methods inside Plaform.ready(), like so:
...
import { Platform } from 'ionic-angular';
import { InAppBrowser } from '#ionic-native/in-app-browser';
...
export class HomePage {
private iab: InAppBrowser;
private platform: Platform;
private browser;
...
var launch = function(url) {
this.platform.ready().then(
() => {
this.browser = this.iab.create( url, "_blank", "EnableViewPortScale=yes,closebuttoncaption=Done" );
this.browser.on("exit").subscribe(
(event) => {
this.close_event = true;
},
(err) => {
console.log("InAppBrowser Loadstop Event Error: " + err);
}
);
}
);
};
...
}
according to my application , I have to notify user whenever he gets disconnected from a network .so in a provider i used two function , one returns true on online state and the other returns true on offline state. In app.component.ts am checking whether app is in online state or not by calling "isOnline()" of the provider.here the provider code..
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { Network } from '#ionic-native/network';
import { Platform } from 'ionic-angular';
import {Observable} from 'rxjs/Rx';
/*
Generated class for the Connectivity provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
declare var Connection;
#Injectable()
export class Connectivity {
onDevice: boolean;
myObservable :any;
constructor(public http: Http,public platform: Platform,public network:Network) {
console.log('Hello Connectivity Provider');
this.onDevice = this.platform.is('cordova');
/*
this.myObservable = Observable.create(observer => {
let result = this.isOffline();
observer.next(result);
});
*/
}
isOnline(): boolean {
if(this.onDevice && this.network.type){
return this.network.type !== Connection.NONE;
} else {
return navigator.onLine;
}
}
isOffline(): boolean {
if(this.onDevice && this.network.type){
return this.network.type === Connection.NONE;
} else {
return !navigator.onLine;
}
}
}
inside the constructor of app.component.ts am calling isOnline()
constructor(platform: Platform,public connectivityService: Connectivity) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
/*this.connectivityService.myObservable.subscribe((data) => {
console.log(data);
});*/
if(this.connectivityService.isOnline()){
console.log("online");
}
else {
console.log("offline");
}
});
this is working fine but, when i get disconnected from network ,i have to refresh the browser again then only am able to see the "offline" on console.how to notify user as soon as network is lost
onchange() method isn't working correctly..
https://github.com/driftyco/ionic-native/issues/1043
I used the solution from the github forum:
Observable.merge(this.network.onConnect(), this.network.onDisconnect())
.subscribe(e => console.log(e), err => console.error(err));
Have a look at the Ionic Native Network documentation.
Particularly the onChange() method:
onchange()
Returns an observable to watch connection changes
Returns: Observable<any>
I am getting this error this.network.onchange(...).subscribe is not a function and I am using ionic native 3.6.0. Looking at the Network native plugin this is how the code looks like.
/**
* Returns an observable to watch connection changes
* #return {Observable<any>}
*/
Network.prototype.onchange = function () {
return Observable.merge(this.onConnect(), this.onDisconnect());
};
Doing the same in your code can fix the issue
import { Observable } from 'rxjs/Observable';
Observable.merge(this.network.onConnect(), this.network.onDisconnect()).subscribe(() => {
this.getNetworkInfo();
});
So I'm trying to get started with ionic 2 from ionic 1 and need some guidance on how to set up authentication in my project. Specifically I'm using firebase and angularfire2.
As a general approach should I either:
a. Check for session/localStorage on app.ts and set the rootPage to login if unauthenticated? Using this method if I log the user out and set the nav rootpage back to the login, the tabs are displayed at the bottom.
b. Create the login page as a modal which removes the problem of the tabs appearing at the bottom, but I'm not sure if I should be firing the modal from app.ts since I'm not sure if the application itself has a root view I should be referencing.
Also, should I set up the auth login and logout as a service and refactor it out rather than having it in the login page and the logout button in the profile controllers?
Here's my logic thus far using method A:
app.ts
export class MyApp {
rootPage: any;
local: Storage = new Storage(LocalStorage);
constructor(platform: Platform) {
this.local.get('user').then(user => {
if (user) {
this.rootPage = TabsPage;
} else {
this.rootPage = LoginPage;
}
});
platform.ready().then(() => {
StatusBar.styleDefault();
});
}
}
And in myProfile.ts
logout() {
this.local.remove('user');
this.user = null;
let modal = Modal.create(LoginPage);
this.nav.present(modal); //should I set the rootPage instead? if so how do I remove the tabBar or set the rootpage of the containing app root page
}
a. Check for session/localStorage on app.ts and set the rootPage to
login if unauthenticated? Using this method if I log the user out and
set the nav rootpage back to the login, the tabs are displayed at the
bottom.
You can use Angularfire2 Ionic Provider , Go to this link for more details Angularfire2 Auth with Ionic
import { Observable } from 'rxjs/Observable';
import { Injectable } from '#angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
// Do not import from 'firebase' as you'll lose the tree shaking benefits
import * as firebase from 'firebase/app';
#Injectable()
export class AuthService {
private currentUser: firebase.User;
constructor(public afAuth: AngularFireAuth) {
afAuth.authState.subscribe((user: firebase.User) => this.currentUser = user);
}
getauthenticated(): boolean {
return this.currentUser !== null;
}
signInWithFacebook(): firebase.Promise<any> {
return this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider());
}
signOut(): void {
this.afAuth.auth.signOut();
}
displayName(): string {
if (this.currentUser !== null) {
return this.currentUser.facebook.displayName;
} else {
return '';
}
}
}
Then from App.ts Import the Provider you just created and then check for Auth status
constructor(public authService: AuthService) {
let authState = this.authservice.getauthenticated();
if (authState) {
this.rootPage = TabsPage;
} else {
this.rootPage = LoginPage;
}
}
And Finally for the Logout use Navigating from an Overlay Component
import { App } from 'ionic-angular';
constructor(
public appCtrl: App
) {}
setRoot(Page:any) {
this.appCtrl.getRootNav().setRoot(Page);
This will not display the Tabs in bottom.
Here's an example of an ionic login flow with a jwt stored in the local storage:
https://github.com/RedFroggy/ionic2-nfc-app/tree/master/app/pages/login