Calling a local notification from background mode Ionic 4 - geolocation

Currently trying to build a location based triggered local notification in ionic 4 - I started by using native background mode (implemented in the initialize App of app.ts) which is working and tracking user location with the watchPosition(). However I'm finding it hard to get the trigger of the local notification to work. My code that I have tried is attached, ant help would be much appreciated!
this.backgroundMode.on('activate').subscribe(() => {
console.log('activated');
const watchLocation = this.geolocation.watchPosition();
watchLocation.subscribe((data) => {
data.coords.latitude;
data.coords.longitude;
console.log('current Position', data.coords.latitude, data.coords.longitude);
this.locationNotification();
});
});
this.backgroundMode.enable();
}
locationNotification() {
this.localNotifcation.schedule({
id: 3,
title: 'Welcome to the show grounds!',
text: 'Click me to declare your entries!!',
sound: '',
trigger: {
type: 'location',
center: [53.3385394, -6.266703],
radius: 1000,
notifyOnEntry: true,
notifyOnExit: false,
single: true
},
vibrate: true,
foreground: true
});
}

Related

How can I add 3 custom sounds in react native iOS?

I want to add 3 custom sounds in react native iOS.
Have any of you ever solved it?
Currently, when I test the FCM Notification by adding and grouping a voice file (.wav) to the iOS project folder, one of the added sounds is coming out.
For example, suppose you have sound files sound01, sound02, sound03, when the backend sends an FCM notification, I want the specified sound to sound at that time.
I solved Android but I don't know how to set in iOS environment.
is iOS has channel like android?
I solved it with the code below in the source receiving Firebase Cloud Messaging (FCM).
// remote message processing function
const sendLocalNotificationWithSound = remoteMessage => {
if (Platform.OS === 'ios') {
PushNotificationIOS.addNotificationRequest({
id: remoteMessage.notification.notificationId
? remoteMessage.notification.notificationId
: new Date().toString(),
title: remoteMessage.notification.title,
subtitle: remoteMessage.notification.message
? remoteMessage.notification.message
: '',
body: remoteMessage.notification.body,
sound: remoteMessage.notification.sound
})
} else {
PushNotification.localNotification({
channelId: remoteMessage.notification.android.channelId,
id: remoteMessage.notification.notificationId
? remoteMessage.notification.notificationId
: new Date().toString(),
title: remoteMessage.notification.title,
message: remoteMessage.notification.body,
soundName: remoteMessage.notification.android.sound,
playSound: true,
smallIcon: 'ic_stat_ic_notification',
color: '#FFFFFF',
largeIcon: '',
largeIconUrl: '',
vibrate: true,
groupSummary: true
})
}
}
// remote message receiving
React.useEffect(() => {
const getMessage = messaging().onMessage(remoteMessage => {
sendLocalNotificationWithSound(remoteMessage)
})
return () => getMessage()
}, [])
First, the react-native-push-notification and #react-native-community/push-notification-ios libraries must be installed.
react-native-push-notification
#react-native-community/push-notification-ios
function messaging() in code is #react-native-firebase/messaging library.
you have to import module like:
import messaging from '#react-native-firebase/messaging'
on head in code
The official documentation for react-native FCM (firebase cloud messaging) is here -> REACT NATIVE FIREBASE
FCM sending side JSON sample file
(I test with postman)
{
"to": "your fcm token here",
"notification": {
"title": "your notification title",
"body": "your notification description",
"sound": "your notification sound name (Runs on iOS)",
"android_channel_id": "your android channel id here (Runs on Android)",
"priority": "high",
"contentAvailable": true,
"mutableContent": 1
},
"data": {
... // if you need data property
}
}

Removing local notification on ios react native

Im developing an app which is connected to a bluetooth device. If the device is disconnected the user receives a push notification that the device is disconnected. This works fine on both android and iOS with this library.
If the application reconnects, then i want to remove the notification. This works fine on android, but does not remove the notification on iOS.
Here is the code for creating notification:
export const pushNotification = (title: string, message: string) => {
PushNotification.localNotification({
channelId: 'channel',
title: title,
message: message,
id: '1',
});
};
export const configurePushNotification = () => {
PushNotification.configure({
requestPermissions: true,
});
};
export const createChannelForPushNotification = () => {
PushNotification.createChannel(
{
channelId: 'channel',
channelName: 'Push Notification Channel',
channelDescription: 'A channel to send push notifications',
soundName: 'default',
importance: Importance.HIGH,
vibrate: true,
},
(created) => console.log(`createChannel returned '${created}'`),
);
};
I use the code below to remove the notification, which works fine on android.
PushNotification.cancelLocalNotification('1');
Any suggestions as to why it is not removing local notification on iOS?

React native Background geolocation updates IOS

This package
I need solution for i want to update location every 30 seconds.
I'm using this package for background geolocation updates when its working fine, but when i move my phone (iphone6) it send my location to firebase. I'm using location changes of this package because postTemplate is not working on IOS device and stoOnStillActivity:true for if activity is still it wont send location.
BackgroundGeolocation.configure({
locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
desiredAccuracy: BackgroundGeolocation.MEDIUM_ACCURACY,
stationaryRadius: 10,
distanceFilter: 10,
debug: true,
interval: 30000,
stopOnStillActivity: true,
})
This one sending location to firebase
BackgroundGeolocation.on('location', (location) => {
BackgroundGeolocation.startTask(taskKey => {
firestore()
.collection('testlocation')
.add({
name: 'DEVICE',
lat: location.latitude,
lon: location.longitude,
dat: new Date,
})
.then(() => {
console.log('Location added BITCH!')
}).catch(e => console.log(e))
console.log("Stark task started successfully", new Date, location.latitude, location.longitude)
BackgroundGeolocation.endTask(taskKey)
})
})

Nativescript | Firebase notification not working

I'm having a problem using firebase in my Nativescript application, when I'm using android its working great but not working with IOS. the problem is on message sending.
I'm using the push-plugin in the client side
This is the register part in the IOS client side using pushPlugin
const iosSettings:any = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
notificationCallbackIOS: (message: any) => {
alert(JSON.stringify(message));
}
};
pushPlugin.register(iosSettings, (token: string) => {
// update the token in the server
alert("Device registered. Access token: " + token);
});
}
}, (errorMessage: any) => {
alert("Device NOT registered! " + JSON.stringify(errorMessage));
});
This is how i receive my token to the push notification,
after a got the token when i'm using the pusher application everything works great, i'm getting the notification in the IOS device
but the problem is when im trying to send the notification from the server!.
I get this error :
Invalid registration token provided. Make sure it matches the
registration token the client app receives from registering with FCM.
Node code in my server
var payload = {
data: {
targetId:userToken,
body: "some text"
}
};
var options = {
priority: "high",
contentAvailable: true,
timeToLive: 60 * 60 * 24
};
Admin.messaging().sendToDevice(userToken, <any>payload,options)
.then((response) => {
console.log('notification arrived successfully', response.results[0]);
})
.catch((error) => {
console.log('notification failed', error);
});
registration token for ios is not the same for android. I encountered the same wall you've encountered. You need to use https://github.com/node-apn/node-apn for IOS push notification. and firebase for android notification. You can do the logic on your backend by saving the token. with a field called type which is ios or android if ios you use node-apn and if android use sendToDevice provided by firebase.
Thats what i'm currently using with my current nativescript projects' I'm working on that involves push notification. Hope that helps you, mate.

Cordova Plugins does not schedule a local notification on an iOS App built on PhoneGap

I'm trying to package a native iOS App using PhoneGap platform. I've added the Cordova library in the config.xml file for the local notification.
I want to schedule two daily notifications (one morning and one evening). When I alert window.plugin.notification.local.add ({ message: 'Great app!' }), it works. However, when the App is loaded, window.plugin.notification.local.add for only evening show up in the tablet notification even though I set the custom date and time for both of them...
Also, cordova.plugins.notification.local.schedule function does not work.
My questions are
1- Why cordova.plugins.notification.local.schedule function does not trigger anything?
2- Why window.plugin.notification.local.add does not schedule the morning notification?
3- What is the difference between cordova.plugins and window.plugin?
I appreciate if anyone can assist me on this...
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
setTimeout(function() { init(); }, 500);//1/2 seconds
//
function init() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
//alert('hello matt');
// Now safe to use the Cordova API
//window.plugin.notification.local.add({ message: 'Great app3!' });
//user premission
window.plugin.notification.local.promptForPermission();
//
var d = new Date();
d.setHours(10);
d.setMinutes(0);
d.setSeconds(0);
window.plugin.notification.local.add({
id: 1, // A unique id of the notifiction
date: d, // This expects a date object
message: 'Make sure to check Today’s Metric Insight for powerful tools that will help to transform you into the most fit, energetic, healthiest version of yourself. ', // The message that is displayed
title: 'TheBigPicture', // The title of the message
repeat: 'daily', // Either 'secondly', 'minutely', 'hourly', 'daily', 'weekly', 'monthly' or 'yearly'
autoCancel: true, // Setting this flag and the notification is automatically canceled when the user clicks it
});
/*
badge: Number, // Displays number badge to notification
sound: String, // A sound to be played
json: String, // Data to be passed through the notification
ongoing: Boolean, // Prevent clearing of notification (Android only)
*/
//
var d2 = new Date();
d2.setHours(19);
d2.setMinutes(0);
d2.setSeconds(0);
window.plugin.notification.local.add({
id: 2, // A unique id of the notifiction
date: d2, // This expects a date object
message: 'Make sure to update your daily Accountability Tracker, and complete your 100 Day Challenge daily survey. ', // The message that is displayed
title: 'TheBigPicture', // The title of the message
repeat: 'daily', // Either 'secondly', 'minutely', 'hourly', 'daily', 'weekly', 'monthly' or 'yearly'
autoCancel: true, // Setting this flag and the notification is automatically canceled when the user clicks it
});
//window.plugin.notification.local.add({ message: 'Great app!' });
cordova.plugins.notification.local.schedule([{
id: 1,
title: 'TheBigPicture',
text: 'Make sure to check Today’s Metric Insight. ',
at: _10_am,
every: 'day'
}, {
id: 2,
title: 'TheBigPicture',
text: 'Make sure to update your daily Accountability Tracker.',
at: _7_pm,
every: 'day'
}]);
//
cordova.plugins.notification.local.on("schedule", function(notification) {
alert('fourth');
alert("scheduled: " + notification.id);
});
}//end of onDeviceReady function
//
</script>
<script>

Resources