I am Creating A Mobile application With Angular 10 + Cordova + Node. Here I have to send some push notification... I have done push notification with Ionic Angular && I have did in this project (web version) Thats working Perfectly with Firebase.. But no idea how to with native (Cordova) .
Asking help For:
How to retrieve device id for Push notification ? (I guess the Back End Part Will Be Same Just Have To Provide The Device Id For Mobile Device)
Here is The code in Backend (For Clearing Confusion)
exports.everyDayDueDate = () => {
task
.find()
.populate([
{
path: "project_id",
model: project,
select: ["project_name"],
},
])
.sort({ status: 1 })
.then((result) => {
result.data.forEach((element) => {
const a = new Date(new Date().toISOString());
const b = new Date(element.taskCompletedate);
if (b.getDate() - a.getDate() == 1) {
User.findById(element.user_id).then((result) => {
if (result) {
let deviceId = result.deviceId;
const payload = {
notification: {
title: element.task_name,
body: "Working!",
},
to: deviceId,
};
const options = {
method: "POST",
uri: "https://fcm.googleapis.com/fcm/send",
body: payload,
json: true,
headers: {
"Content-Type": "application/json",
Authorization:
"key=AAAAL0qgxio:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
},
};
request(options);
}
});
}
});
});
};
I just need to provide the device id to my backend, How Can I get That
*** Not Ionic ***
cordova plugin add cordova-plugin-device
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.uuid);
}
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-device/index.html
Related
Nice to meet you.
I'm junior developer.
I made hybrid app(webview) by react natvie expo + php + mysql
this application have a push notification.
When I click on this, I want to go to a specific page. This page should go to a specific page, not the main page, not open browser by chrome, Safari... when the app opens.
how to make it?? please, help me.
Below is the code I made.
useEffect(() => {
registerForPushNotificationsAsync().then((token) => {
let url = "myUrl";
fetch(url, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: JSON.stringify({ token: token }),
})
.then()
.catch((err) => console.log(err));
setExpoPushToken(token);
});
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
const url = response.notification.request.content.data.url;
// console.log(url); i can see specific url.
Linking.openURL(url);
// IntentLauncher.startActivityAsync("android.intent.action.View", {data: url});
});
return () => {
if (
typeof notificationListener.current !== "undefined" &&
typeof responseListener.current !== "undefined"
) {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
}
};
}, []);
Hey guys i been debugging for long but still can't fix the problem.
I get 403 Forbidden laravel broadcasting/auth using pusherjs for private channel. on pusher dashboard logs i can see the event but on browser not firing the event.
frontend code reactjs
const enablePusher = () => {
var pusher = new Pusher('XXXXXXXXXXXXXX', {
cluster: 'mt1',
authEndpoint: Setting.BASE_URL + '/broadcasting/auth',
auth: {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
},
})
var channel = pusher.subscribe(`private-mc-chat-conversation.${conversation.id}`)
channel.bind('.Musonza\\Chat\\Eventing\\MessageWasSent', data => {
console.log(JSON.stringify(data))
})
}
BroadcastServiceProvider.php
Broadcast::routes(['middleware' => ['auth:api']]);
Channels.php
Broadcast::channel('presence-mc-chat-conversation.{conversationId}', function ($user) {
return ['id' => $user->id, 'name' => $user->name];
});
I am stuck on one of the mysterious issue. The problem goes like this:
What I Do??
Simply do login api call and if login success then I have to fetch amount of data from 5-6 api calls and store them in local database (Realm). Here is my code.
login(email, password) {
this.toggleLoadingFunction(true);
fetch(LoginURL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
request_from: 'mobile'
}),
})
.then(async res => {
if (res.ok) {
let data = await res.json();
global.user = data['user']
global.token = data['token']
getAllMasterDataAndSaveInRealm().then(() => {
this.toggleLoadingFunction(false);
global.storage.save({ key: 'LoggedInData', data: data });
this.props.navigation.navigate('Project', data);
}).catch(() => {
this.toggleLoadingFunction(false);
Alert.alert("Master Data Failed !!!");
})
} else {
this.toggleLoadingFunction(false);
let data = await res.json();
Alert.alert("Login Failed!!!", data.message)
}
})
.catch(error => {
this.toggleLoadingFunction(false);
Alert.alert("Network Error. Please try again.")
})
Here getAllMasterDataAndSaveInRealm() is lies on helper function which calls 5-6 apis and response back if all work is done. Here is how it looks like:
export const getAllMasterDataAndSaveInRealm = () => {
const token = global.token;
return new Promise.all([
getMaterials(token),
getEquipments(token),
getObjective(token),
getCategories(token),
getNcData(token),
getPlans(token)]
);
}
Each function inside getAllMasterDataAndSaveInRealm() returns Promise after successfully stored data in local realm db. Here is one of the above function.
export const getActivityPlan = (token) => {
return new Promise((resolve, reject) => {
return fetch(FetchActivityPlanDataURL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access_token': `${token}`
}
}).then((response) => {
console.log("Activity Plans Api response", response);
return response.json()
})
.then((responseJson) => {
const { data } = responseJson
console.warn("Activity Plans Api", data);
global.realm.write(() => {
for (var item of data) {
item.id = item.id ? item.id : 0;
item.activity_id = item.activity_id ? item.activity_id.toString() : "";
item.activity_name = item.activity_name ? item.activity_name.toString() : "";
item.activity_cost = item.activity_cost ? item.activity_cost.toString() : "";
item.project_id = item.project_id ? item.project_id : 0;
global.realm.create("ActivityPlan", item, true);
}
})
resolve(data);
})
.catch((error) => {
reject(`Activity Plan Failed ${error}`)
});
})
}
All remaining functions are same as above ( what they do is simply fetch data from api and store it in realm and resolve or reject)
What I Expect:
getAllMasterDataAndSaveInRealm() function Just store all the required data in db and let me know all done and then navigate to the another screen, as Login and fetching data is done.
Problem:
When I do run the app and process for login, Sometimes it works fine but most of the time App stuck on showing loader since some of the api call among 6 api from above do not get response from the request ( I do log the response) on wifi. But when I use mobile data and VPN it always works.
When I log request on server console, response is sent with code 200, but app is unable to get response for the request.
I am new on react native. I do lots of searches over internet but unable to find the solution. I don't have any idea whats going wrong with the code. Please help me out.
Project Configurations:
"react": "16.8.6",
"react-native": "0.60.4",
"realm": "^2.29.2",
Node version: v9.0.0
I have the following code for creating an event with a image and some body params. It was working fine when i was doing it without image, i am using react-native-image-crop-picker for selecting images. I am getting "Network request failed" error when posting data from react-native. The request never reach my backend as i am getting no logs there. It is working fine with postmen.
MY CODE:
const { name, date, description, location, uri, mime, time } = this.state;
const formData = new FormData();
formData.append('name', name)
formData.append('date', date)
formData.append('description', description)
formData.append('location', location)
formData.append('time', time)
formData.append('image',{
uri:uri,
mime:'image/jpeg',
name:`image${moment()}`
})
alert(JSON.stringify(formData));
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
};
fetch(`http://${Config.apihost}:${Config.port}/events`,config).then((res) => res.json())
.then((res) => {
this.setState({ modalVisible: false, name:'', date: moment().format('YYYY-MM-DD'), description:'', Location: 'AlHedaya Masjid' })
this.props.addEvent(res.message);
// this.props.navigation.goBack();
}).catch((err) => alert(err));
I have another screen which contains different number of pictures like gallery i am uploading multiple picture to the gallery, the request is working fine with code below.
const data = new FormData();
data.append('name', 'avatar');
images.map((res, i) => {
data.append('fileData[]', {
uri: res.path,
type: res.mime,
name: `image${i}${moment()}`
});
})
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
};
fetch(`http://${Config.apihost}:${Config.port}/events/${this.state.item.id}/photos`, config)
.then((checkStatusAndGetJSONResponse) => checkStatusAndGetJSONResponse.json())
.then((response) => {
if (response.status && response.message.length > 0) {
var images = this.state.images;
response.message.map(file => {
images.push(`http:${Config.apihost}:${Config.port}/images/${file.id}`);
});
this.setState({ images });
}
}).catch((err) => { alert(err) });
I can't really see the difference between the two codes but the upper code giving me error.
I am testing on android
I am using the IP address instead of localhost (my others requests are working so thats out of equation)
None of the solution in this link worked
React Native fetch() Network Request Failed
Am I missing something?
In first code snippet you have written mime instead of type.
formData.append('image',{
uri:uri,
**mime:'image/jpeg**',
name:`image${moment()}`
})
it should be like below snippet
formData.append('image',{
uri:uri,
type:'image/jpeg',
name:`image${moment()}`
})
so im trying to make a App that loads all the thing in the loading screen/splash/auth screen.
So I in the basic I have a Welcome, Login and Home screen for now.
Welcome will be showing if the App is open for first time, Login if the user is opening the App without login or is logged out before closing the App and Home will be open if the user is logged in.
Here is the simply check:
componentDidMount() {
AsyncStorage.getItem("alreadyLaunched").then(value => {
if (value == null) {
AsyncStorage.setItem('alreadyLaunched', 'true'); // No need to wait for `setItem` to finish, although you might want to handle errors
this.setState({ firstLaunch: 'true' });
}
else {
this.setState({ firstLaunch: 'false' });
}
})
}
loadApp = async () => {
const userToken = await AsyncStorage.getItem('userToken')
setTimeout(
() => {
if (this.state.firstLaunch == 'true') {
this.props.navigation.navigate('Welcome')
} else {
if (userToken) {
this.props.navigation.navigate('App')
} else {
this.props.navigation.navigate('SignIn')
}
}
}, 0
);
}
And if the login is correct I just put this on Async:
AsyncStorage.setItem("userToken", "logged");
This for now its working perfectly, but I need to get 3-4 for functions to get information to the server then State It. Here is one of the functions:
getSignalsCount = async (username, password) => {
try {
var DeviceInfo = require('react-native-device-info');
//AUTH
fetch(Config.SERVER_URL + '/mob/auth', {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "1",
id: "",
sessId: "",
data: {
u: username,
p: password,
}
})
}).then((response) => response.json())
.then((res) => {
let res_code = res['code'];
let session = "";
let cl_id = 0;
let name = "";
if (res_code == 51) {
session = res['session'];
cl_id = res["data"]["response"]["client_id"];
name = res["data"]["response"]["name"];
this.setState({fullName:name});
//GET STATS
fetch(Config.SERVER_URL + '/mob/sport/getSignalsInfo', { //home
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "9",
sessId: session,
data: {
devId: '1234567890',
devName: DeviceInfo.getUniqueID(),
u: username,
client_id: cl_id,
type: {
nums: 50000,
period: 12
}
}
})
}).then((response) => response.json())
.then((res) => {
var closed = res["data"]["response"]["data"]["closed"];
var opened = res["data"]["response"]["data"]["open"];
this.setState({ total_active_signals: opened, total_closed_signals: closed })
})
.done();
}
})
.done()
}
};
So if set this function on the Auth.js and then use it on the same screen with {this.state.total_active_signals} will show me the varible.
But I need it to be show also on HOME or maybe LOGIN and other pages that I may created in future. So I basic need this state to be use on maybe every screen.
I tried to create a global.js with:
module.exports = {
username: '',
};
And then in HOME:
//.....
import global from '../../global'
//....
<Text>Username: {GLOBAL.username}</Text>
But the question now is how to fill the global.js with the state so that, Home/Login/Profile/Stuff screens to get it later.
Thanks!
You basically have two options:
Use Redux and create an app wide state (store) to which all
components have access to (recommended). Your idea of a global state
fits pretty good with the concept of redux.
Pass data as props between components. You can also use a navigation library
to deal with this (e.g. react navigation or react native router
flux)