How to implement pushwoosh with ionic 2 - push-notification

I want to implement pushwoosh in ionic 2 i am using this cordova plugin. i am new to ionic 2 want to know how to use methods from this plugin.

First read the pushwoosh manual about using the cordova plugin: http://docs.pushwoosh.com/docs/cordova-phonegap
After that i got this code working on ios and android.
On step 3, you can use the following code as a service provider:
in my projects folder i created this file: /src/app/providers/push-service.ts
import { Injectable } from "#angular/core";
import { Platform } from 'ionic-angular';
declare var cordova : any;
#Injectable()
export class PushService {
PUSHWOOSH_APP_ID : string = 'XXXXX-XXXXX'; // your pushwoosh app id
GOOGLE_PROJECT_NUMBER: string = 'XXXXXXXXXXXX'; // project number from firebase
constructor(public platform : Platform){
this.platform.ready().then(() => {
if(this.platform.is('ios') || this.platform.is('android')){
console.log("PushwooshService init: Running on push compatible platform "+ this.platform.userAgent() +')');
this.initPushwoosh();
} else{
console.log("PushwooshService init: No compatible platform available. Skipping init.)");
return;
}
});
}
initPushwoosh(){
let pushNotification = cordova.require("pushwoosh-cordova-plugin.PushNotification");
//set push notifications handler
document.addEventListener('push-notification', function (event) {
let message = (event as any).notification.message; // Push message
let userData = (event as any).notification.userdata; // Custom push data
if (userData) {
// handle custom push data here
console.log('user data: ' + JSON.stringify(userData));
}
});
//initialize Pushwoosh with projectid: "GOOGLE_PROJECT_NUMBER", pw_appid : "PUSHWOOSH_APP_ID". This will trigger all pending push notifications on start.
pushNotification.onDeviceReady({
appid: this.PUSHWOOSH_APP_ID,
projectid: this.GOOGLE_PROJECT_NUMBER
// serviceName: "MPNS_SERVICE_NAME"
});
//register for pushes
pushNotification.registerDevice(
function (status) {
var pushToken = status;
console.log(pushToken);
alert('push token: ' + JSON.stringify(pushToken));
},
function (status) {
alert(JSON.stringify(['failed to register ', status]));
}
);
}
}
Now you can import this provider in your /src/app/app.component.ts.
import { PushService } from '../providers/push-service';
#Component({
templateUrl: 'app.html',
providers: [PushService]
})
Whenever your app is launched, it will initialize pushwoosh.
Good luck ;)

You need to use
var message = (event as any).notification.message;
Instead of
var message = event.notification.message;

Related

How to use Coinbase SDK in a Server-Side Rendered app?

I was trying to follow the guide here to get user's wallet through Coinbase in my Next.js app:
https://docs.cloud.coinbase.com/wallet-sdk/docs/initializing
But I get this when I tried to render the component with the SDK initiating.
Server Error
ReferenceError: localStorage is not defined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Is there a proper way to make it work in a server-side rendered app?
These are the code btw if that matters.
// Coinbase START
// TypeScript
import CoinbaseWalletSDK from '#coinbase/wallet-sdk'
import Web3 from 'web3'
const APP_NAME = process.env.NAME
const APP_LOGO_URL = process.env.WEBSITE_URL + '/logo.png'
const DEFAULT_ETH_JSONRPC_URL = 'https://mainnet.infura.io/v3/' + process.env.INFURA_PROJECT_ID
const DEFAULT_CHAIN_ID = 1
// Initialize Coinbase Wallet SDK
export const coinbaseWallet = new CoinbaseWalletSDK({
appName: APP_NAME,
appLogoUrl: APP_LOGO_URL,
darkMode: false
})
// Initialize a Web3 Provider object
export const ethereum = coinbaseWallet.makeWeb3Provider(DEFAULT_ETH_JSONRPC_URL, DEFAULT_CHAIN_ID)
// Initialize a Web3 object
export const web3 = new Web3(ethereum as any)
// Coinbase END
Related call:
function connectCoinBase() {
console.log('connectCoinBase is triggered');
if (ethereum && mounted) {
setLoading(true);
ethereum.request({
method: 'eth_requestAccounts'
})
.then((res) => {
const accounts: string[] = res as string[];
if (accounts && accounts.length) {
setWalletId(accounts[0]);
setWalletType(2);
connectCrypto();
}
setLoading(false);
})
.catch(err => {
console.error('Coinbase eth_requestAccounts failed, error: ', err);
setLoading(false);
})
}
}
The error was thrown without calling this function but happens when this function is added and the page is rendered.
UPDATE: This error is related to the ScopedLocalStorage class inside the #coinbase/wallet-sdk dependency. The localStorage is not available in server-side rendering.

Phoneauthprovider is not a function firebase react-native

Hi everybody im making a app using react-native and fire base im have this initial config at firebase config :
import firebase from 'firebase/app';
import 'firebase/auth';
import Constants from 'expo-constants';
// Firebase Config
// Initialize Firebase
export const firebaseConfig = {
apiKey: Constants?.manifest?.extra?.apiKey,
authDomain: Constants?.manifest?.extra?.authDomain,
projectId: Constants?.manifest?.extra?.projectId,
storageBucket: Constants?.manifest?.extra?.storageBucket,
messagingSenderId: Constants?.manifest?.extra?.messagingSenderId,
appId: Constants?.manifest?.extra?.appId
};
let Firebase
if (firebase.apps.length === 0) {
console.log('hello world')
Firebase = firebase.initializeApp(firebaseConfig);
}
export default Firebase;
And im triyng to call this method:
const loginUser = async() => {
switch(loginType){
case 0:
break;
case 1:
if (typeof(verificationId) == 'string') {
setLoading(true)
try {
const credential = new Firebase.auth.PhoneAuthProvider.credential(
verificationId,
verificationCode
);
await Firebase.auth.signInWithCredential(credential);
showMessage({ text: 'Phone authentication successful 👍' });
} catch (err) {
setLoading(false)
showMessage({ text: `Error: ${err.message}`, color: 'red' });
}
} else {
try {
const phoneProvider = Firebase.auth.PhoneAuthProvider();
const verificationId = await phoneProvider.verifyPhoneNumber(
phoneNumber,
recaptchaVerifier.current
);
setVerificationId(verificationId);
showMessage({
text: 'Verification code has been sent to your phone.',
});
} catch (err) {
showMessage({ text: `Error: ${err.message}`, color: 'red' });
}
}
break;
}
}
When im try to call my 'phone Login method' react-native show me this message:
im use this guide for how to configure the enviroment:
https://blog.jscrambler.com/how-to-integrate-firebase-authentication-with-an-expo-app
but using phone verification with recaptcha im not found the problem i believe the problem its in my implementation but in not found nothing
Thanks for the answers
I see you're trying to implement phone auth using firebase and I personally had success doing that using this:
async function signInWithPhoneNumber(phoneNumber) {
//1. Have the user input thei phone number into a TextInput and pass it to this function
//2. Have a confirm useState to make sure the verification code was sent successfully by firebase
//3. Check for the confirm state in the main component and show the user another TextInput to enter the verification code if confirm has a value
await firebase.auth()
.signInWithPhoneNumber(phoneNumber)
.then(confirmation => {
setConfirm(confirmation)
})
.catch(e => {
Alert.alert('Error sending verification code to this phone number')
})
}
async function confirmCode(code) {
//1. Have the code the user entered through the TextInput pass through here and call the below function
try {
let validation = await confirm?.confirm(code)
if (validation) console.log('correct code.')
} catch (error) {
Alert.alert('Invalid code.')
}
}
You're importing your own Firebase object, which is an instance of FirebaseApp. The PhoneAuthProvider class is not defined on FirebaseApp, but rather is in the (static) firebase.auth namespace.
So you either need to also import the regular Firebase Auth SDK into your code, instead of just your own Firebase object, or you can attach the firebase.authnamespace to yourFirebase` object and use it from there with:
...
if (firebase.apps.length === 0) {
console.log('hello world')
Firebase = firebase.initializeApp(firebaseConfig);
Firebase.auth = firebase.auth;
}
export default Firebase;

How to implement Firebase phone authentication with Ionic 4?

Is it possible to use phone authentication with Firebase and Ionic 4 in mobile apps?
I have seen some old tutorials implementing phone authorization with Ionic 3, but these seem to be outdated.
The firebaseui-web project does not support phone authentication for cordova apps, but I am unsure if that implies that Firebase phone authentication is impossible with ionic apps.
If you cannot use Firebase's phone authentication with Ionic 4, is there an alternative phone authentication service that does work with Ionic 4?
Yes. You can do it with Firebase's Javascript SDK, it will need the user to pass a CAPTCHA and then send the phone number a verification code which you can login and auth with, the process is explained here:
https://firebase.google.com/docs/auth/web/phone-auth#send-a-verification-code-to-the-users-phone
The problem is that the firebase auth sms service will only send messages when the app is in production mode (uploaded to the store). But to be able to test the methods from test mode, it is adding a test number in the white list of firebase.
In my case, I try these:
sms-verification.page.ts
sendSmsVerification(phoneNumber): Promise <firebase.auth.UserCredential> {
return new Promise((resolve, reject) => {
firebase.auth().useDeviceLanguage();
var verificationId;
var code;
const timeOutDuration = 60;
const tell = '+54' + phoneNumber;
this.FireBase.verifyPhoneNumber(tell, timeOutDuration).then(async (credential) => {
// alert(credential.instantVerification);
if (credential.verificationId) {
console.log("Android credential: ", credential);
verificationId = credential.verificationId;
} else {
console.log("iOS credential: ", credential);
verificationId = credential;
}
if (credential.instantVerification) {
code = credential.code;
this.verifySms(verificationId, code)
.then( resp => {
resolve(resp);
})
.catch( err => {
reject(err);
});
} else {
let prompt = await this.alertCtrl.create({
backdropDismiss: false,
header: 'Ingrese el codigo de confirmación del SMS.',
inputs: [{ name: 'confirmationCode', placeholder: 'Código de confirmación' }],
buttons: [
{ text: 'Cancelar',
handler: data => {
console.log('Cancel clicked');
resolve(data);
}
},
{ text: 'Verificar',
handler: data => {
code = data.confirmationCode;
this.verifySms(verificationId,code)
.then( resp => {
resolve(resp);
})
.catch( err => {
reject(err);
}); }
}
]
});
prompt.present();
}
}).catch(error => {
console.log('Error! Catch SMSVerificacion', error);
reject(error);
});
})
}
verifySms(verificationId, code): Promise <any> {
console.log('parametros de verifySms ', verificationId +' ', code);
const signInCredential = firebase.auth.PhoneAuthProvider.credential(verificationId,code);
return firebase.auth().signInAndRetrieveDataWithCredential(signInCredential);
}
Yes, it's possible to use firebase phone authentication using Cordova plugin,
cordova-plugin-firebase-authentication
Add this plugin to your ionic 4 project
cordova plugin add cordova-plugin-firebase-authentication --save
With this we can verify phone without using reCaptcha.
Note that this only work on real android device, not emulator or browser.
Function implementation
verifyPhoneNumber(phoneNumber, timeout)
cordova.plugins.firebase.auth.verifyPhoneNumber("+123456789", 30000)
.then(function(verificationId) {
// pass verificationId to signInWithVerificationId
});
or
AngularFire (With reCaptcha)
https://github.com/angular/angularfire
First, install angularfire lib into your project
npm install firebase #angular/fire --save
then import this lib into your class
import * as firebase from 'firebase/app';
code example:
firebase.auth().signInWithPhoneNumber(phoneNumber,recaptchaVerifier)
.then(confirmationResult => {
this.windowRef.confirmationResult = confirmationResult;
})

ionic 2 Offline Data Sync using Azure Mobile Apps throws TypeError:Cannot read property 'openDatabase' of undefined

I have created ionic 2 app using visual studio template and trying to develop Offline Data Sync in Azure Mobile Apps functionality.
I have installed node "module of azure-mobile-apps-client" and
using as import * as WindowsAzure from 'azure-mobile-apps-client'; in app.components.ts and initializing store using
Client = new WindowsAzure.MobileServiceClient("url"); but error showing me as "TypeError:Cannot read property 'openDatabase' of undefined".
I have also installed #ionic-native/sqlite node module and cordova-sqlite-storage plugin.
Please see below code:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { NavController } from 'ionic-angular';
//declare var WindowsAzure: any;
import * as WindowsAzure from 'azure-mobile-apps-client';
var mobileAppClient, // Connection to the Azure Mobile App backend
store, // Sqlite store to use for offline data sync
syncContext, // Offline data sync context
tableName
var useOfflineSync: boolean = true;
#Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
constructor(public navCtrl: NavController, public platform:Platform) {
platform.ready().then(() => {
mobileAppClient = new WindowsAzure.MobileServiceClient("https://myapp.azurewebsites.net");
// Create the sqlite store
store = new WindowsAzure.MobileServiceSqliteStore('store.db');
store.defineTable({
name: 'todoitem',
columnDefinitions: {
id: 'string',
text: 'string',
complete: 'boolean',
version: 'string'
}
});
// Get the sync context from the client
syncContext = mobileAppClient.getSyncContext();
// Initialize the sync context with the store\
syncContext.initialize(store).then((syc) => {
// Get the local table reference.
tableName = mobileAppClient.getSyncTable('todoitem');
// Sync local store to Azure table when app loads, or when login complete.
syncContext.push().then((res) => {
// Push completed
// Pull items from the Azure table after syncing to Azure.
syncContext.pull(new WindowsAzure.Query('todoitem')).then((data) => {
alert(JSON.stringify(data));
}, (err) => {
alert(err);
});
});
}, function (err) {
alert(err);
});
});
}
}
This is probably your client database table columns doesn't match your remote database. Note that removing a column via migration doesn't remove the column in SQLite.

Firebase Authentication on Ionic 2

I am trying to implement login with firebase on Ionic 2 with the following code.
export class MyApp {
rootPage:any = Login;
isAuthenticated = false;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
firebase.initializeApp({
apiKey: "AIzaSyC94rD8wXG0aRLTcG29qVGw8CFfvCK7XVQ",
authDomain: "myfirstfirebaseproject-6da6c.firebaseapp.com",
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
this.rootPage = Home;
} else {
this.rootPage = Login;
}
});
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();
});
}
}
I realize that even when I am authenticated, I am always brought to the Login screen because it does not wait for onAuthStateChanged promise to be fulfilled and carries on with initializing the app, therefore, the Login screen instead of the Home screen is always shown.
But how should I change my code so that I can show Home when authenticated?
Remove the login from the rootPage declaration
export class MyApp {
rootPage:any;
...
}
You're setting the page to your LoginPage as the app initializes and before he can check if the user is loged.
For it to run the onAuthStateChange, when the app initializes you need to use Zone to create an observable and the run it.
import { NgZone } from '#angular/core';
zone: NgZone; // declare the zone
this.zone = new NgZone({});
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
this.zone.run(() => {
if (user) {
this.rootPage = Home;
unsubscribe();
} else {
this.rootPage = Login;
unsubscribe();
}
});
});
Hope it helps

Resources