I'm developing an Android Application using Ionic 3 and I want to use push notification with tool OneSignal. Here is the code that I use at my main component:
let iosSettings = {
kOSSettingsKeyAutoPrompt: true,
kOSSettingsKeyInAppLaunchURL: false
}
this.oneSignal
.startInit(APP_ID, GOOGLE_PROJECT_NUMBER)
.iosSettings(iosSettings);
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
this.oneSignal
.handleNotificationReceived()
.subscribe((notification: OSNotification) => {
console.log(notification)
});
this.oneSignal.endInit();
And here is the code that I use at my node webservice:
function sendNotification(scheduling) {
const schedulingID = scheduling.email + scheduling.date;
const message = {
app_id: APP_ID,
headings: {"en": MY_APP_NAME},
contents: {"en": "Scheduling confirmed!"},
data: {"agendamento-id": schedulingID},
included_segments: ["All"]
};
const headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic " + REST_API_KEY
};
const options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
console.log("Sending notification...");
const req = https.request(options, function (res) {
res.on('data', function (data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function (e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(message));
req.end();
}
But, when I execute the Android App on my devices, I get the message error:
{id: '', recipients: 0, errors: ['All included players are not subscribed']}
This will solve your problem:
'included_segments' => array(
'Subscribed Users'
),
Related
I'm trying to send a fetch request using post to an api, I'm doing a search using a keyword and it should return a JSON containing users, whenever I try this on Android using expo it doesn't work however it seems to work on iOS using expo. The error I get back is a JSON parse error, I get a status code of 308.
import User from '../../Model/User';
import { BearerToken } from '../../Constants/BearerToken';
export const GETRESULTS = 'GETRESULTS';
export const getResults = (item) => {
return async dispatch => {
const response = await fetch("https://example.com",
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': BearerToken
},
body: JSON.stringify({
query: item
}),
redirect: 'follow'
}
);
console.log(response.status);
if(!response.ok) {
console.log("fack off");
const errorResData = await response.json();
console.log(errorResData);
let message = 'Something went wrong';
throw new Error(message);
}
const resData = await response.json();
const searchResultsArray = [];
for(const searchResult in resData){
searchResultsArray.push(new User(
resData[searchResult].education,
resData[searchResult].email,
resData[searchResult].full_name,
resData[searchResult].gender,
resData[searchResult].job_title,
resData[searchResult].location,
resData[searchResult].password,
resData[searchResult].phone,
resData[searchResult].preferred_name,
resData[searchResult].profile_image,
resData[searchResult].profile_type,
resData[searchResult].score,
resData[searchResult].short_bio,
resData[searchResult].story
)
);
}
dispatch({type: GETRESULTS,usersArray:searchResultsArray});
};
};
What worked for me was putting 'https://example.com/search/' basically at a slash at the end fixed it for me
I'm trying to send/upload image file to my back-end serve using fetch multipart upload in react-native, but fetch multipart form data upload is not working for android, however I tried different examples.
Image upload multipart form data API is based on php and its working for iOS react-native app.
I am using react-native-photo-upload library for taking image.
storePicture(PicturePath:string) {
console.warn(PicturePath);
if (PicturePath) {
const apiUrl = `${Constants.APIHOST}updateprofileimage.php`;
// Create the form data object
var data = new FormData();
data.append('profileimage', { uri:PicturePath, name: 'profileimage.jpg', type: 'image/jpg/jpeg' });
data.append('accesstoken', this.state.user.sAccessToken);
data.append('react-native', 1);
// Create the config object for the POST // You typically have an OAuth2 token that you use for authentication
const config = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data;' }, body: data };
fetch(apiUrl, config)
.then(responseData => { // Log the response form the server
// Here we get what we sent to Postman back
console.warn(`response:${responseData}`);
})
.catch(err => {
console.warn(err);
});
}}
Here is the example how I am calling storePicture() function.
<PhotoUpload onResizedImageUri={
avatar => {
if (avatar) {
this.storePicture(avatar.path);
}
}}
>
<Image source={{uri: this.state.user.sProfileImageUrl}} style={{resizeMode:"cover", marginTop:8.0, backgroundColor:'transparent', height:120.0, width:120, borderRadius:60.0, borderWidth:0.0, borderColor:'transparent'}}/>
</PhotoUpload>
uploadProfileImage = async (image:var) => {
this.setState({
loading: true
});
var RNFS = require('react-native-fs');
const path = Style.IS_IOS ? image.uri : image.path;
var fileName = path.split('/').pop();
var fileType = fileName.split('.').pop();
var filePath = Style.IS_IOS ? path : 'file://' + path;
const apiURL = `${Constants.APIHOST}updateprofileimage.php`;
const formData = new FormData();
formData.append('accesstoken', this.state.user.sAccessToken);
formData.append('reactnative', 1);
formData.append('profileimage', {
uri:filePath,
name: fileName,
type: `image/${fileType}`,
});
try {
const response = await fetch(apiURL, {
body: formData,
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json',
},
})
const json = await response.json()
this.handleUploadImageResponse(json);
} catch (err) {
this.setState({
loading: false
},console.log('catch Error: '+ err));
}
}
I am answering my own question as I haven't found any valid answer for the sake of other users, who are facing same issue.
Please let me know if I can improve my answer/post or in case any help is needed from me.
Image Upload to an API by Multipart FormData
uploadPicture = () => {
console.log(
"Image Upload urI = " + JSON.stringify(this.state.imageSourceUri.uri)
);
this.setState({ loading: true });
const form = new FormData();
form.append("fileToUpload", {
uri: this.state.imageSourceUri.uri,
type: "image/jpg",
name: "12334"
});
fetch("http://119.82.97.221/HPBSProjectApi2/api/HPBS/PostFormData", {
method: "post",
body: form
})
.then(response => response.json())
.then(response => {
console.log("response = " + response);
this.setState({
loading: false
});
});
};
the problem is the type field in the FormData, use mime to resolve it. Images must be image/jpeg.
const formData = new FormData();
formData.append("image",{..., name, uri, type: mime.getType(uri)}));
I'm building an application that uses Firebase and OneSignal with client written in unity3d, the problem is that I want to receive notification but do not want it to display notifications when the app is not running.
https://documentation.onesignal.com/docs/android-customizations#section-background-data-and-notification-overriding
This is the code from Firebase, everything runs fine
enter code here
var sendNotification = (data) => {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic YzA3MjYwZmMtNzUwYi00YWFiLThjNGUtYjYzMGM4NmM1ZWRl"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var req = https.request(options, (res) => {
res.on('data', (data) => {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', (e) => {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "752aef3b-5a0a-44be-8e94-f31d648cb866",
contents: {"en": "English Message"},
included_segments: ["All"]
};
sendNotification(message);
And I want to hide the notification when the app is not running,
like this one
I already follow the instruction on Ionic 3 documentation about Push notification.
When I try to send the notification and my app on background, I cannot trigger 'notification' event so I cannot go through specific page.
But when my app is on foreground, the 'notification' event triggered automatically.
I use:
Ionic 3 as the mobile framework
Firebase Cloud Messagins as the message service
Laravel with larave-fcm plugin to send message
Backend - Laravel code for push message to firebase
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20)->setContentAvailable(true);
$notificationBuilder = new PayloadNotificationBuilder('Hello');
$notificationBuilder->setBody('Hello world')->setSound('default');
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['custom' => 'test']);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$token = "token";
$downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
$success = $downstreamResponse->numberSuccess();
$failure = $downstreamResponse->numberFailure();
$modification = $downstreamResponse->numberModification();
echo 'Success: '.$success;
echo "<br>";
echo 'Failure: '. $failure;
echo "<br>";
echo 'Modification: '.$modification;
print_r($downstreamResponse->tokensToDelete());
echo "<br>";
print_r($downstreamResponse->tokensToModify());
echo "<br>";
print_r($downstreamResponse->tokensToRetry());
echo "<br>";
print_r($downstreamResponse->tokensWithError());
FRONTEND - My ionic apps constructor on app.component.ts
constructor(private translate: TranslateService, private platform: Platform, settings: Settings, private config: Config, private statusBar: StatusBar, private splashScreen: SplashScreen, public push: Push, public alertCtrl: AlertController, public storage: Storage, private backgroundMode: BackgroundMode) {
this.initTranslate();
this.platform.ready().then(() => {
if(!this.backgroundMode.isActive) {
this.backgroundMode.setDefaults({silent: true});
this.backgroundMode.enable();
} else {
this.backgroundMode.disable();
this.backgroundMode.setDefaults({silent: true});
this.backgroundMode.enable();
}
this.pushSetup();
this.storage.get('test').then((val) => {
if(val == 'news'){
this.nav.setRoot(TabsPage);
}
});
});
}
Function pushSetup()
pushSetup() {
const options: PushOptions = {
android: {
senderID: '10524067XXXXX'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
if(notification.additionalData.foreground){
let myAlert = this.alertCtrl.create({
title: 'Push',
message: JSON.stringify(notification)
});
myAlert.present();
} else {
this.storage.set('test', 'news');
}
});
pushObject.on('registration').subscribe((registration: any) => {
console.log(registration);
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
I found the answer from
here.
I should send to fcm with like this
{
"data" : {
"title": "Test Notification",
"body": "This offer expires at 11:30 or whatever",
"notId": 10,
"surveyID": "ewtawgreg-gragrag-rgarhthgbad"
}
}
On laravel fcm just set title, body, notId on addData function from PayloadDataBuilder.
I want to add notifications to an online android chatting app I have made. I am new to cloud functions, so I tried using the code given here https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html
My index.js file
var firebase = require('firebase-admin');
var request = require('request');
var API_KEY = "xyz"; // Your Firebase
Cloud Messaging Server API key
// Fetch the service account key JSON file contents
var serviceAccount = require("firebase.json");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://firebaseio.com/"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notificationRequests');
requests.on('child_added', function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
console.log('notificationrecived, sent and removed- ' +
request.username + ' '+ request.message,);
requestSnapshot.ref.remove();
}
);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '
+response.statusMessage);
}
else {n
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
I have successfully deployed this code to the server using node.js command line.
But this does not show up on the console and nor the logs that I added to debug
and the code doesn't seem to work. I have done everything given in the link i mentioned. I could use some help on how to fix my code
I don't know how big of a difference this makes, but in the Firebase admin set up page https://firebase.google.com/docs/admin/setup, it is mentioned that for Cloud Functions, the following line is sufficient for initialisation:-
var firebase = require('firebase-admin');
firebase.initializeApp(functions.config().firebase);
So, if you're going by the book, you may replace the initialisation line in your code with the one above and try running it again.
I didn't export my function listenForNotificationRequests() but called it only once at the end of the script.
Which is why it didn't show up on the Firebase Console.
I fixed this by simply exporting the function like this
exports.sendFollowerNotification = listenForNotificationRequests;