I am trying to update live activities using remote push notifications.
I am creating a live activity like this:
do{
let activity = try Activity<LiveMatchesAttributes>.request(attributes: attributes, contentState: state, pushType: .token)
print("Activity Added Successfully. id: \(activity.id)")
Task {
for await data in activity.pushTokenUpdates {
let myToken = data.map {String(format: "%02x", $0)}.joined()
print("pushToken", myToken)
}
}
}catch{
print(error.localizedDescription)
}
The live activity shows up in the notifications center and the pushToken can also be received.
Now I am trying to update the live activity using remote notifications. The code for that looks like this:
exports.updateLiveActivities = functions.https.onRequest((req, res) => {
const fcmToken = "fcmToken"
const apns = {
headers: {
"apns_push_type" : "liveactivity",
"apns_topic" : "bundle_id.push-type.liveactivity",
},
"payload": {
"aps": {
"timestamp" : Date.now(),
"event": "update",
"content-state": {
"event": "start"
},
"alert": {
"title": "Race Update",
"body": "Tony Stark is now leading the race!"
}
},
}
}
const message = {
token: fcmToken,
apns: apns
}
admin.messaging().send(message).then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
res.send("ok")
// return res.send("ok");
}).catch((error) => {
console.log(error)
return res.send(error.code);
});
});
Sending the remote notification works because the "alert" is appearing on my phone but the live activity is not getting updated. Any ideas where to insert the received "pushToken" for the live activity?
Related
i have this payload below that send push from firebase function. the payload send notification successful to Android. now i am confused about the iOS.
my Question is that:
will this also send to iOs because i can see that there is no alert in the payload in apsn.
i fellow the documentation in this site which they did not give ios payload.
when i make a research on iOs payload i can see something like this
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
but in the documentation i cant found where they give alert
exports.chatFunctions = functions.firestore.document("chat/{chatId}/Messages/{messagesId}").onCreate(async (snapshot, context) => {
if (!snapshot.exists) {
console.log('No Device');
}
const chatDatas = snapshot.data();
const messageTo = chatDatas['idTo'];
const deviceTokenuUser1 = await admin.firestore().collection('users').doc(messageTo).get();
const user1name = deviceTokenuUser1.data()['name'];
const user1Url = deviceTokenuUser1.data()['profilePictureUrl'];
let payload = {
notification: {
title: `${user1name}`,
body: `${chatDatas['content']}`,
},
data: {
key: 'chat',
id: `${messageTo}`,
click_action: "FLUTTER_NOTIFICATION_CLICK"
},
android: {
priority: "high",
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
token: deviceTokenuUser1.data()['tokens'],
};
try {
await admin.messaging().send(payload);
console.log("Firebase chat Messaging Successfully");
} catch (err) {
console.log("error from chat messaging " + err);
}
i am using push notification with local notification.. i have to set channel id in my payload..
here is my payload
i am not sure if this is payload for both andriod and ios. please help me out with correct payload.
thanks
exports.chatFunctions = functions.firestore.document("chat/{chatId}/Messages/{messagesId}").onCreate(async (snapshot, context) => {
if (!snapshot.exists) {
console.log('No Device');
}
const chatDatas = snapshot.data();
const messageTo = chatDatas['idTo'];
const deviceTokenuUser1 = await admin.firestore().collection('users').doc(messageTo).get();
const user1name = deviceTokenuUser1.data()['name'];
const user1Url = deviceTokenuUser1.data()['profilePictureUrl'];
let payload = {
notification: {
title: `${user1name}`,
body: `${chatDatas['content']}`,
},
data: {
key: 'chat',
id: `${messageTo}`,
click_action: "FLUTTER_NOTIFICATION_CLICK"
},
android: {
priority: "high",
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
token: deviceTokenuUser1.data()['tokens'],
};
try {
await admin.messaging().send(payload);
console.log("Firebase chat Messaging Successfully");
} catch (err) {
console.log("error from chat messaging " + err);
}
You can add channel id like this:
let payload = {
// ...
android: {
priority: "high",
notification: {
channelId: "yourchannelid"
}
}
// ...
}
I have Ionic Native Push notification enabled on my app, that's through FirebaseX.
My problem is that I get notification if the app is open in foreground but if it's in Background I get nothing.
When I pull up the app, it delivers.
Can anybody shine a light?
Here is my service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { FirebaseX } from '#ionic-native/firebase-x/ngx';
import { AngularFirestore } from '#angular/fire/firestore';
import { Platform } from '#ionic/angular';
import { LoginService } from './login.service';
#Injectable()
export class FCMProvider {
constructor(
public firebaseX: FirebaseX,
public afs: AngularFirestore,
private platform: Platform,
private loginService: LoginService
) {}
async getToken() {
let token;
if (this.platform.is('android')) {
token = await this.firebaseX.getToken();
}
if (this.platform.is('ios')) {
const hasPermission = await this.firebaseX.hasPermission();
if (!hasPermission) {
await this.firebaseX.grantPermission();
} else {
token = await this.firebaseX.getToken();
}
}
console.log(token);
return this.saveTokenToFirestore(token);
}
saveTokenToFirestore(token: string) {
if (!token) {
return;
}
const devicesRef = this.afs.collection('devices');
let userOs;
if (this.platform.is('ios')) {
userOs = 'ios';
} else {
userOs = 'android';
}
const docData = {
token,
os: userOs,
userID: this.loginService.getUID()
};
return devicesRef.doc(token).set(docData);
}
listenToNotifications() {
return this.firebaseX.onMessageReceived();
}
}
and on my app.component.ts I got this right after deviceReady:
pushNotification() {
this.fcProvider.getToken();
this.fcProvider.listenToNotifications()
.pipe(
tap(msg => {
const toast = this.toastCtrl.create({
message: msg.body,
duration: 4000
});
toast.then(a => a.present());
})
)
.subscribe();
}
I'm sending the messages though postman:
{
"to": "e749fugfe793hfhwifh8988799f:...",
"name": "my_notification",
"data": {
"title": "Test",
"body": "This is just a test notification",
"notification_foreground": "true",
"notification_body" : "Notification body",
"notification_title": "Notification title",
"forceStart": "1"
},
"priority": "high"
}
I have been struggling recently with this topic, to hear notifications in the background you have to subscribe to a subscription which you will get in platform.pause (platform is a variable of type Platform from #ionic/angular).
Inside of this subscription you should listen the firebaseX notifications.
I hope my answer has helped you, if you have any questions don't hesitate to ask me.
Am trying to update the json data through an api call.
I was able to GET the data without any issues, as am not passing any Options in the request.
For UPDATE,
//saga.js
export function* BlurideaTitler(opt) {
const id = opt.id; // 4
const updatedTitle = opt.newTitle; // "title changed"
let options = {
crossDomain: true,
method: 'PUT',
json: true,
headers: {'Content-Type': 'application/json'},
body: {
title: updatedTitle
}
};
const requestURL = `http://localhost:3000/ideas/${id}`;
try {
yield call(request, requestURL, options);
} catch (err) {
console.log(err);
}
}
// request.js
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
}
//db.json
JSON am trying to update.,
{
"ideas": [
{
"id": 4,
"title": "My fourth Idea",
"body": "Description of my fourth idea",
"created_date": "14-Apr-2019"
}
]
}
This is supposed to update the value of title. But it throws error'Bad request' . Can someone please let me know what am missing here.
I am using ionic.io to send push to my app. I have following body
{"tokens":["DeviceToken"],
"profile":"Profile",
"notification":{ "payload": {
"type": "loadCategories"
},
"ios": {
"content_available": 1
},
"android": {
"content_available": "1"
}}}
Type script code.
var push = Push.init({
android: {
senderID: "ID"
},
ios: {
alert: "true",
badge: true,
sound: 'false'
},
windows: {}
});
if((<any>push).error) {
console.log((<any>push).error);
return;
};
push.on('registration', (data)=>{
console.log(data.registrationId);
this.pushToken = data.registrationId;
this.updateToken();
});
push.on("notification", (data)=>{
console.log(data);
// if(data.additionalData.payload && data.additionalData.payload.type == 'categoryEvent') {
// console.log("at date")
// }
});
push.on('error', function(e) {
console.log(e.message);
});
Idea is that I need to send push to user and load data from the server. But problem is that if app is in background then notification event is not fired. It works only if app is active. But as soon as i understand from documentation it should work.
Known issue that has been addressed with setting content_available = 1. See https://github.com/phonegap/phonegap-plugin-push/issues/93 for more.