Ionic push notification error- 'undefined' not a function Ionic.User.anonymousId() - android

I'm new in ionic framework, developing one simple app using ionic framework. Implementing push notification,
am following below link
https://devdactic.com/android-push-notifications/
went up to final step:
$ionicPlatform.ready(function() {
var io = Ionic.io();
var push = new Ionic.Push({
"onNotification": function(notification) {
alert('Received push notification!');
},
"pluginConfig": {
"android": {
"iconColor": "#0000FF"
}
}
});
var user = Ionic.User.current();
if (!user.id) {
user.id = Ionic.User.anonymousId();
}
// Just add some dummy data..
user.set('name', 'Simon');
user.set('bio', 'This is my little bio');
user.save();
var callback = function(data) {
push.addTokenToUser(user);
user.save();
};
push.register(callback);
});
After this run the below commend
ionic serve -w safari
getting the below error in console ( check last line)
Ionic Core: init
ionic.io.bundle.min.js:2Ionic Core: searching for cordova.js
ionic.io.bundle.min.js:2Ionic Core: attempting to mock plugins
app.js:26TypeError: 'undefined' is not a function (evaluating 'Ionic.User.anonymousId()')
if i run "ionic info" getting following lines
Your system information:
Cordova CLI: 6.1.0 (cordova-lib#undefined)
Ionic Version: 1.2.4
Ionic CLI Version: 1.7.14
Ionic App Lib Version: 0.7.0
OS: Windows 7 SP1
Node Version: v5.0.0
Dependency warning - for the CLI to run correctly,
it is highly suggested to install/upgrade the following:
Please install your Cordova CLI to version >=4.2.0 npm install -g cordova

The Ionic Platform has now moved to Beta status. Part of this change is the introduction of the Platform API and User authentication. We've deprecated the alpha API for the Users and Push services and will be removing them entirely in the coming months.
Users now require Authentication, so Ionic.User.anonymousId(); is not available.
Have a look at Migrations and user usage.

Related

Notifications not coming when app is closed on Ionic

I have an Ionic project. I can receive notifications when the app is open. But when the app is closed, notifications do not come. After sending 2-3 notifications, the application gives a closed warning. How can I receive notifications when the app is closed?
Ionic info:
Ionic:
Ionic CLI : 6.20.1 (C:\Users\xxxxx\AppData\Roaming\npm\node_modules\#ionic\cli)
Ionic Framework : #ionic/angular 6.5.0
#angular-devkit/build-angular : 13.2.6
#angular-devkit/schematics : 13.2.6
#angular/cli : 13.2.6
#ionic/angular-toolkit : 6.1.0
Cordova:
Cordova CLI : 11.0.0
Cordova Platforms : android 10.1.2
Cordova Plugins : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 5.0.0, (and 9 other plugins)
Utility:
cordova-res : 0.15.4
native-run : 1.7.1
System:
NodeJS : v18.13.0 (C:\Program Files\nodejs\node.exe)
npm : 9.3.0
OS : Windows 10
cordova-plugin-fcm-with-dependecy-updated 7.8.0 "Cordova FCM Push
Plugin"
My Code:
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
public route: Router,
public xDevice: Device,
private network: Network,
private fcm:FCM,
) {
this.initializeApp();
this.setupFCM();
}
private async setupFCM() {
this.platform.ready().then(() => {
try {
this.fcm.getInitialPushPayload().then((payload) => {
if(payload?.wasTapped) {
console.log("Received FCM when app is closed -> ", JSON.stringify(payload));
// call your function to handle the data
//this._handlePushNotificationData(payload);
}
});
this.fcm.requestPushPermission();
this.fcm.hasPermission();
this.fcm.getToken().then(token => {
console.log("Token: " + token);
console.log(token)
}).catch(error => {
console.log(error)
})
this.fcm.onNotification().subscribe(data => {
if (data.wasTapped) {
console.log('Received in background');
} else {
console.log('Received in foreground');
}
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log(token)
});
} catch (error) {
console.log(error)
}
});
}
It asks for permission for notification, but when the application is closed, the notification does not come. I can't find the problem either because the app is closed. How can I solve this problem?
The issue you are facing is likely caused by the way Firebase Cloud Messaging (FCM) handles push notifications when the app is closed. FCM uses a notification tray icon to display push notifications when the app is closed. However, the notification may not appear if the user has disabled the notification tray icon for your app.
To troubleshoot this issue, you can try the following:
Ensure that you have correctly set up FCM in your app and that the correct credentials are being used.
Check if the notification tray icon is enabled for your app in the device settings.
Make sure that the FCM server key and sender ID are correctly configured in the Firebase console.
Check if the device token is being correctly retrieved and sent to the FCM server.
5.Test the notifications on different devices and see if the issue is specific to a certain device or if it's happening on all devices.
If the issue is still not resolved, you can try using a different push notification service or library that is better suited for handling push notifications when the app is closed.

Expo v27/v28 Android App with websocket is crashing

Environment: Android 6 Marshmallow and iOS(all versions)
Error: Android app with WebSockets is crashing with error:
WebSocketModule.close got 1 arguments, expected 3.
The error happens when I close the WebSocket connection just on Android, for instance:
this.ws = new WebSocket(url);
this.ws.onopen = () => {
const command = { command: 'JOIN', room: roonHash };
this.ws.send(JSON.stringify(command));
};
this.ws.onmessage = e => {
//more code here
};
// Finally:
this.ws.close();
iOS:
On iOS it works fine.
I'm using Expo v27 but I got the same error on v28.
Is there any workaround fixing that until the Expo/React Native team fixes it forever?
Expo v27
Update your React Native/Expo v27.0.0 to v27.0.2 on your package.json
Expo v28
Update your React Native/Expo v28.0.0 to v28.0.1 on your package.json
Procedures:
1) Go to your package.json file and change the version of your expo, for example:
From:
"react-native": "https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz",
To:
"react-native": "https://github.com/expo/react-native/archive/sdk-27.0.2.tar.gz",
2) Delete your node_modules:
$ rm -rf node_modules
3) Install it again:
$ yarn install

Ionic3-Cordova-UWP : Ionic Storage doesn’t work when app is running

I have a problem with Ionic storage in my Ionic App for Windows (UWP app). I already tested and deployed my app for Android without any trouble.
Now I would like to generate an UWP app.
The app I’m developing is a workshop’s dashboard. The indicators change every day and I need to save them from one day to another. To do this I usethe storage module of Ionic.
When launching the command
$ionic serve
the app responds exactly as it should in the web browser (Firefox). From one launch to another my data are still there.
When I use
$ionic cordova run windows
the installation and launch steps of my app work fine. Every function of my app runs fine, but the call to storage (get and set) doesn’t work : when I close, and then reopen it as an autonomous application, I loose all data every time. It is the same when I run the app from Visual Studio.
Moreover, I write some console.log in the result of the promise and none of them is written in the Javascript console. It is like Windows does not recognize the command.
I tried with Visual Studio 2015 Update 3 and Visual Studio 2017, the result is identical. I followed the recommendation of Ionic Doc and add the target platform windows10 in the config.xml.
Does anyone have an idea of what I’m doing wrong ? Is there an incompatibility between Windows and Ionic ?
Thanks for any help.
Config :
Windows 10 64-bits
Ionic CLI: 3.19.1
Cordova CLI : 8.0.0
Node : v6.11.2
Visual Studio Community 2017 (15.5.27130.2036)
Extract of my code maPage.ts :
import { Storage } from '#ionic/storage';
export class maPage {
constructor(public storage: Storage) {
this.downloadData();
}
ionViewWillLeave()
{
this.saveData();
}
TabData = {
id: 0,
label: '',
Tab1: [],
Tab2: [],
attri1 : 0,
attri2: false
}
Param = {
Objet1: {NbObj1: 7},
Objet2: {NbObj2: 5}
}
saveData()
{
var Data: object;
Data =
{
TData: this.TabData,
TParam: this.Param
}
this.storage.set('Data', Data).then(_=> {
console.log('Backup done!');
}, error => {
console.log('erreur : ', JSON.stringify(error))
});
}
downloadData()
{
this.storage.ready().then(()=>{
console.log('storage ready');
this.storage.get('Data').then((val) => {
this.TabData = val.TData;
this.Param = val.TParam;
console.log('Récupération terminée !');
}).catch(erreur => {
console.log('La variable Data est vide ou n\'existe pas!');
console.log('erreur : ', JSON.stringify(erreur));
}).catch(err => {
console.log('storage not ready');
console.log('err : ', JSON.stringify(err));
});
}
}
On Windows platform, console.log is not supported. To do that, you should install cordova-plugin-console, or need to use alert function.
Regarding storage, I am suggesting you could use localstorage or cordova-sqlite-storage.

Http requests fails only while releasing Android APK

I'm struggling in making my app work on Android APK release, the only scenario it fails is at generating and signing the apk. All http requests doesn't work. (The server is running under SSL)
All Scenarios I've tried already:
ionic serve -> Works fine.
ionic cordova run android --device -> Works fine.
Works on emulators as well.
Also works fine generating the iOS build:
ionic cordova build ios.
On Xcode, running build targeting a real device.
On Xcode, archiving and uploading it to Itunesconnect then downloading it from AppStore once it's accepted by Apple.
So, the only case it doesn't work is when I try to generate it's apk through ionic cordova build android --prod --release and signing it.
Google Play also accepts the new APK, so there's no problem with the package sign at all.
Since it works on iOS and running directly on android device, it isn't a CORS or HTTPS certificate problem.
The code:
snippet of login.ts:
this.userService.loginUser(this.user).then(
(data) => {
let response = data.json();
loading.dismiss().then(loadData => {
if (response.access_token) {
this.global.access_token = response.access_token;
this.getUserData();
}
});
}, err => {
let error = err.json();
loading.dismiss().then(response => {
if (error.message) {
this.showToast(error.message, 3000, 'bottom');
}
});
}
);
userService.loginUser method:
loginUser(data) {
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('auth-token', '*');
return this.abs.post('/authenticateMobile',
{
login_ds_email: data.email,
login_ds_password: data.pass
}, headers);
}
Where abs is:
constructor(http) {
this.abs = new ApiService(http);
}
ApiService.post method:
public post(api, params, header): any {
if (!header) {
header = this.getHeaders();
}
let options = new RequestOptions({headers: header});
let url = this.global.urlGlobal + api;
return this.http.post(url, params, options).toPromise();
}
The App gets stuck when I fire "login" button and the request is made. There's no exception thrown by the server, so the loading screen is shown forever.
I've running out of solutions for this and I hope you guys can help me out.
Ionic info:
global packages:
#ionic/cli-utils : 1.4.0
Cordova CLI : 6.4.0
Gulp CLI : CLI version 3.9.1 Local version 3.9.1
Ionic CLI : 3.4.0
local packages:
#ionic/app-scripts : 1.3.0
#ionic/cli-plugin-cordova : 1.4.0
#ionic/cli-plugin-gulp : 1.0.1
#ionic/cli-plugin-ionic-angular : 1.3.1
Cordova Platforms : android 6.0.0 ios 4.3.1
Ionic Framework : ionic-angular 3.0.1
System:
Node : v7.8.0
OS : macOS Sierra
Xcode : Xcode 8.3.3 Build version 8E3004b
ios-deploy : 1.9.0
ios-sim : 5.0.6
npm : 5.0.3
I had this exact same issue some time ago. In my case the problem was an invalid certificate. The certificate looked fine to me in the browser (chrome even showed the green lock), on iOS and while testing on Android. But I had android-users complain it wasn't working for them.
After hours of researching it turned out that requests to websites with invalid certificates just get silently dropped, which means there is no feedback whatsoever. No errors, nothing. (If I remember correctly, the js code just stopped executing without returning or executing any callbacks.) This happens ONLY when building in release mode.
A workaround is described here:
http://ivancevich.me/articles/ignoring-invalid-ssl-certificates-on-cordova-android-ios/
The best way to handle it would be to pin the certificate in your app.
My issue was incomplete SSL chain, solve it by reconfiguring nginx to have the entire chain of SSL certificates as described here:
http://nginx.org/en/docs/http/configuring_https_servers.html#chains
My problem was with SSL as well. If you get an "A+" rating from this website, it should work. My original grade was "B".
https://www.ssllabs.com/ssltest
You can use this site to correct it.
https://whatsmychaincert.com/

Ionic v2 create project issue

I'm trying to get ionic2 up and running by following the Getting Started page. I ran the npm -g install cordova ionic command in step one and everything seemed fine but when I ran step two ionic start --v2 myApp tabs I received errors.
CCasadMBP:Sites ccasad$ ionic start --v2 myAppv2 tabs
/Users/ccasad/.npm-packages/lib/node_modules/ionic/node_modules/ionic-app-lib/lib/start_wizard.js:94
ps.stdout.on('data', (data) => {
^^
SyntaxError: Unexpected token =>
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.start_wizard (/Users/ccasad/.npm-packages/lib/node_modules/ionic/node_modules/ionic-app-lib/index.js:25:12)
at Object.<anonymous> (/Users/ccasad/.npm-packages/lib/node_modules/ionic/lib/ionic/start.js:13:30)
at Module._compile (module.js:460:26)
/Users/ccasad/.npm-packages/lib/node_modules/ionic/node_modules/ionic-app-lib/lib/start_wizard.js:94
ps.stdout.on('data', (data) => {
^^
Unexpected token => (CLI v2.2.1)
Your system information:
Cordova CLI: 6.5.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
ios-deploy version: 1.8.2
ios-sim version: 5.0.3
OS: OS X Yosemite
Node Version: v0.12.6
Xcode version: Xcode 7.2.1 Build version 7C1002
I've had things running fine for ionic v1 so not sure why things in npm aren't working for v2. The error almost seems like it doesn't understand ES6 arrow functions or something since it's saying unexpected token on the =>.
Any ideas how to deal with this? Do I need to reinstall node?
Thanks
Best way uninstall and delete node from C:\Program Files or C:\Program Files (x86) and install the latest version.
OR
This is a ionic bug in this file
C:\Users\{user}\AppData\Roaming\npm\node_modules\ionic\node_modules\ionic-app-lib\lib\start_wizard.js
For compile this syntax of node.js you need to new version of Node.js and so you must be change all lambda syntax from function to normalize codes for older versions:
ps.stdout.on('data', (data) => {
var d = data.toString('utf-8');
if(d.indexOf('dev server running') >= 0) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
'status': 'success'
}));
}
process.stdout.write(d);
});
To :
ps.stdout.on('data',function (data) {
var d = data.toString('utf-8');
if(d.indexOf('dev server running') >= 0) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
'status': 'success'
}));
}
process.stdout.write(d);
});
Full Correct file : Download
I am not sure this way it could work for you, even i had a issue i have resolved this way . I believe look like node migration issue .Try to set latest version (e.g 6.9.4).Before doing do clean npm and then install.Hope this should work

Categories

Resources