Ionic native secure storage plugin fails silently (on Ionic View and Ionic Dev App on Android) - ionic-framework

I have added Ionic Secure Storage plugin (to store authentication tokens) into my Ionic project, and it works properly locally when running cordova run browser (so that cordova is loaded as a plaform).
However, when I open my project in Ionic DevApp and Ionic View on Android (works correctly on iOS), it fails silently whenever I try to retrieve the saved token.
Here is my code:
// ... unrelated imports omitted
import {Platform} from "ionic-angular";
import {SecureStorage, SecureStorageObject} from "#ionic-native/secure-storage";
#Component({
selector: 'my-component',
templateUrl: 'my-component.html'
})
export class MyComponent {
constructor(private platform: Platform,
private secureStorage: SecureStorage) {
}
ngOnInit() {
this.getToken().then(token => {
// ... do something with the retrieved token
});
}
getToken() {
if (this.platform.is('cordova')) {
/**
* Code below silently fails in Ionic View and Ionic Dev App
* on Android (works correctly on iOS)
*/
return this.platform.ready().then(() =>
return this.secureStorage.create('cp_secure_storage')
.then((storage: SecureStorageObject) => {
return storage.get('TOKEN_NAME')
.then(token => {
console.log(token);
return token;
}, () => null);
});
});
} else {
return Promise.resolve(localStorage.getItem('TOKEN_NAME'));
}
}
}
I have Ionic error monitoring turned on and it catches no errors.
Plugin version:
"#ionic-native/secure-storage": "4.5.3",
"cordova-plugin-secure-storage": "^2.6.8"

Related

How to use Pushwoosh in Ionic 5 project with capacitor

Hi everyone I am migrating an app from ionic 1 to ionic 5 and I need to integrate the pushwoosh notification service, my project was started not using cordova, instead I use capacitor and I can't find information about how to integrate this service to an ionic 5 application.
Please, we already know that you can use cordova but when using the cordova plugin add pushwoosh-cordova-plugin#8.0.0 it gives you the following message:
Current working directory is not a Cordova-based project.
because as I said before it is a capacitor project not a cordovan project, Btw I already use ionic integrations enable cordova
So... if anyone can help us, It would be very helpful.
OK guys after many hours trying to integrate Pushwoosh into an ionic 5 application for me it was impossible,
If you set everything up correctly, the following will happen:
Your app will connect to Pushwoosh correctly
Your app will correctly register your device in pushwoosh
But your app will not listen to the listeners offered by the official Pushwoosh documentation
document.addEventListener('push-receive',
function (event) {
var message = (<any>event).notification.message;
var userData = (<any>event).notification.userdata;
alert("Push message received: " + message);
console.info(JSON.stringify((<any>event).notification));
//dump custom data to the console if it exists
if (typeof (userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
}
);
This does not work in an ionic 5 app 👆🏽
This does work:
import { Component, OnInit } from '#angular/core';
import {
Plugins,
PushNotification,
PushNotificationToken,
PushNotificationActionPerformed,
} from '#capacitor/core';
const { PushNotifications } = Plugins;
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
ngOnInit() {
console.log('Initializing HomePage');
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
PushNotifications.requestPermission().then(result => {
if (result.granted) {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener(
'registration',
(token: PushNotificationToken) => {
alert('Push registration success, token: ' + token.value);
},
);
PushNotifications.addListener('registrationError', (error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotification) => {
alert('Push received: ' + JSON.stringify(notification));
},
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
alert('Push action performed: ' + JSON.stringify(notification));
},
);
}
}
I tried to combine Pushwoosh with the capacitor but the tokens of the devices that are generated are different so I still didn't get my notifications.
At the end of the day and after many hours and days of work I have no other option than to use firebase and now everything is going much better.

Ionic 5 Capacitor FileTransfer

I'm running in the browser an ionic 5 APP using capacitor and I'm trying to use the file transfer functionality. I follow the documentation https://ionicframework.com/docs/native/file-transfer and configure my app using capacitor. Thus running:
npm install cordova-plugin-file-transfer
npm install #ionic-native/file-transfer
ionic cap sync
In my app.module, I registered the providers:
import { FileTransfer } from '#ionic-native/file-transfer/ngx';
import { File } from '#ionic-native/file/ngx';
...
providers: [
StatusBar,
SplashScreen,
...
FileTransfer,
File
],
Note that I also installed the native file package, so in total I have the following 4 new packages:
"#ionic-native/file": "^5.27.0",
"#ionic-native/file-transfer": "^5.27.0",
"cordova-plugin-file": "^6.0.2",
"cordova-plugin-file-transfer": "^1.7.1",
My code in the component is:
import { Input, Component } from '#angular/core';
import { FileTransfer, FileTransferObject } from '#ionic-native/file-transfer/ngx';
import { File } from '#ionic-native/file/ngx';
#Component({
selector: 'app-order-detail-order-card',
templateUrl: './order-detail-order-card.page.html'
})
export class OrderDetailOrderCardPage {
#Input() pdfUrl: string;
#Input() orderCardId: string;
constructor(private transfer: FileTransfer, private file: File) { }
public downloadFile(): void {
const fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.download(this.pdfUrl, this.file.applicationDirectory + `${orderCardId}.pdf`).then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
}
When I run the app in the browser, I get the following warning and I'm not sure whether the file should donwload somewhere?
common.js:284 Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
Even if I don't get the file, I would be expecting to see the "download complete" message. It's not very clear to me as to whether I have to configure something else in my app to be able to run it locally or I have to use this functionality ONLY in either the emulator or the device itself.
What else needs to be configured to get this to work?
common.js:284 Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
this means that you are using the browser emulator which doesn't have any splashscreen, you can totally ignore that warning ( you won't get it using a simulator or a real device).
You should paste the html section of that page too, because probably the download doesn't start because an incomplete url and it doesn't proceed with the "then()"
maybe i'm wrong, but it can be possible.

Ionic app: Keeping the screen unlock and open when the ionic app is up and running

I'm developing a navigation app with Ionic framework. Is there a way to keep the screen of the device open while the app is up and running ?
Yes you can Keep screen Active:
There is a cordova plugin for this:
ionic cordova plugin add cordova-plugin-insomnia
npm install #ionic-native/insomnia
import { Insomnia } from '#ionic-native/insomnia/ngx';
constructor(private insomnia: Insomnia) { }
...
this.insomnia.keepAwake()
.then(
() => console.log('success'),
() => console.log('error')
);
this.insomnia.allowSleepAgain()
.then(
() => console.log('success'),
() => console.log('error')
)
Check Plugin Docs here Cordova Insomnia Docs
The answer by Najam Us Saqib is correct but for some minor corrections.
Corrections to the above answer: The IONIC Native package doesnt exist anymore. We need to use Awesome-Cordova-plugins package.
npm install #awesome-cordova-plugins/insomnia
A slightly modified version of the code would be
import { Insomnia } from '#awesome-cordova-plugins/insomnia/ngx';
export class MyComponent implements OnInit, OnDestroy {
constructor(private insomnia: Insomnia) {
this.insomnia.keepAwake()
.then(
() => console.log('success'),
() => console.log('error')
);
}
ngOnDestroy() {
...
this.insomnia.allowSleepAgain()
.then(
() => console.log('success'),
() => console.log('error')
);
...
}
}
The above code will keep the app awake as long as this component is in the stack. Once the component is destroyed, the app will allow the device to sleep again.

Ionic 3 #ionic-native/push "plugin is not installed"

I have to use push notifications in my app, so I followed this tutorial to add the ionic native push.
When I run the app on Android console prints this warning message:
Native: tried calling PushNotification.init, but the PushNotification
plugin is not installed.
I have installed the module with:
$ ionic cordova plugin add phonegap-plugin-push
$ npm install --save #ionic-native/push
How can it be?
My code here:
I added the provider to my app.module.ts:
import { Push } from '#ionic-native/push';
...
providers: [
StatusBar,
SplashScreen,
Services,
Globals,
Push,
Globalization,
Facebook,
GoogleMaps,
Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler},
{ provide: LOCALE_ID, useValue: 'es' },
{ provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig }
]
And in my app.component.ts I have this:
import { Component } from '#angular/core';
import { Platform, ModalController, MenuController, App, AlertController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
import { TabsPage } from '../pages/tabs/tabs';
import { LogregPage } from '../pages/logreg/logreg';
import { FavoritosPage } from '../pages/favoritos/favoritos';
import { MaptestPage } from '../pages/maptest/maptest';
import { Globals } from '../providers/globals';
import { Services } from '../providers/services';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any;
// rootPage:any = TabsPage;
// rootPage:any = LogregPage;
constructor(public appCtrl: App, public platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public modalCtrl: ModalController,
private push: Push, public menuCtrl: MenuController, public globals: Globals, private services: Services, public alertCtrl: AlertController) {
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();
/// Here we try to start the push services
this.initPushNotification();
/// This checks if user session is open
this.globals.checkSession(
(checked) : void => {
if ( checked ) {
this.rootPage = TabsPage;
} else {
this.rootPage = LogregPage;
}
}
);
});
}
/**
* This method is the same as the example :)
*
*/
initPushNotification() {
if (!this.platform.is('cordova')) {
console.warn('Push notifications not initialized. Cordova is not available - Run in physical device');
return;
}
const options: PushOptions = {
android: {
senderID: 'YOUR_SENDER_ID'
},
ios: {
alert: 'true',
badge: false,
sound: 'true'
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((data: any) => {
console.log('device token -> ' + data.registrationId);
//TODO - send device token to server
});
pushObject.on('notification').subscribe((data: any) => {
console.log('message -> ' + data.message);
//if user using app and push notification comes
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: 'New Notification',
message: data.message,
buttons: [{
text: 'Ignore',
role: 'cancel'
}, {
text: 'View',
handler: () => {
//TODO: Your logic here
console.log('Push notification recived');
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
console.log('Push notification clicked');
}
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin' + error));
}
}
EDIT:
After removing and then adding android platform, I get this error runing the app:
BUILD SUCCESSFUL
Total time: 3.207 secs
Subproject Path: CordovaLib
Starting a Gradle Daemon (subsequent builds will be faster)
+-----------------------------------------------------------------
| cordova-android-support-gradle-release: 26.+
+-----------------------------------------------------------------
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
at build_9ug1ggkhhrzygsw0k34tph6ua.run(/Users/[edited path]/platforms/android/build.gradle:143)
FAILURE: Build failed with an exception.
* Where:
Script '/Users/[edited path]/platforms/android/phonegap-plugin-push/tusclases-push.gradle' line: 35
* What went wrong:
A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
> For input string: "+"
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 5.408 secs
Error: /Users/[edited path]/platforms/android/gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.
* Where:
Script '/Users/[edited path]/platforms/android/phonegap-plugin-push/tusclases-push.gradle' line: 35
* What went wrong:
A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
> For input string: "+"
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
[ERROR] An error occurred while running cordova run android (exit code 1).
Hi if you want resolve this problem you must follow these instructions (windows10)
ionic cordova platform rm android
rm platform (platforms folder)
rm plugin (plugins folder)
ionic cordova platform add android
ionic cordova build android
AND enjoy it !!!

Ionic 2 App - Not making any Ajax calls via IOS Simulator

I have been trying to run this app through simulator.
When I run ionic emulate ios, this app will not make any Ajax Calls
When I run ionic emulate ios -c -l this app works perfectly
This is my provider class which I copied pretty much exactly from the Ionic Conference App
import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Storage,SqlStorage} from 'ionic-framework/ionic';
/*
Generated class for the RafitoData provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class RafitoData {
static get parameters() {
return [[Http]];
}
constructor(http) {
this.http = http;
this.districts = null;
this.storage = new Storage(SqlStorage);
}
addCustomer(customer) {
// don't have the data yet
return new Promise(resolve => {
var headers = new Headers();
headers.append('Content-Type','application/json');
var partialURL = '/rafitows/userInfo/create';
var body = JSON.stringify(customer);
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.post(partialURL,body,{headers:headers})
.map(res => res.json())
.subscribe(data => {
resolve(data.status);
}, err=> {console.log(err)});
});
}
}
I am not sure what am I doing wrong. I have the cordova whitelist plugin.
This is my ionic information:
Cordova CLI: 5.4.0
Ionic Version: 2.0.0-beta.1
Ionic CLI Version: 2.0.0-beta.17
Ionic App Lib Version: 2.0.0-beta.8
ios-deploy version: Not installed
ios-sim version: 5.0.6
OS: Mac OS X El Capitan
Node Version: v5.3.0
Xcode version: Xcode 7.2.1 Build version 7C1002
I have uploaded the whole project on gitHub
https://github.com/alyn000r/testAjax/tree/master/testAjax
Please add the below line to your config.xml
<allow-navigation href="*" />
Also have a look here.
Hope this helps you. Thanks.