How to check iceconnectionstate in peerjs - webrtc

how to know the "iceconnectionstate" is changed?
this is what i'm doing
conn.on("iceconnectionstatechange",function (){
alert("state changed");
})

Related

How to get pushToken from react-native-onesignal?

1 year ago, I got pushToken successfully in my react-native app. But right now official website sample code was changed, so I couldn't find any code how to get pushToken.
This is the code I used last year. (Class component)
constructor(props) {
super(props);
...
OneSignal.addEventListener('ids', this.onIds);
}
componentWillUnmount() {
OneSignal.removeEventListener('received', this.onReceived);
OneSignal.removeEventListener('opened', this.onOpened);
OneSignal.removeEventListener('ids', this.onIds);
}
onIds(device) {
console.log('Device info: ', device); // I got pushToken here successfully last year.
}
This is my current code. (Functional component)
useEffect(() => {
// OneSignal Init Code
OneSignal.setAppId("My-OneSignal-Key");
OneSignal.setLogLevel(6, 0);
// END OneSignal Init Code
// Prompt for push on iOS
OneSignal.promptForPushNotificationsWithUserResponse(response => {
console.log("Prompt response:", response);
});
// Method for handling notifications received while app in foreground
OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
console.log("OneSignal: notification will show in foreground:", notificationReceivedEvent);
let notification = notificationReceivedEvent.getNotification();
console.log("notification: ", notification);
const data = notification.additionalData
console.log("additionalData: ", data);
// Complete with null means don't show a notification.
notificationReceivedEvent.complete(notification);
});
// Method for handling notifications opened
OneSignal.setNotificationOpenedHandler(notification => {
console.log("OneSignal: notification opened:", notification);
});
}
But now, where should I get pushToken?
I found this in the doc:
const deviceState = await OneSignal.getDeviceState();
so I think it could be something like:
const deviceState = (await OneSignal.getDeviceState()).pushToken;
Look inside the notification object of setNotificationOpenedHandler or setNotificationWillShowInForegroundHandler.

ASync/Await is not working as expected in router.BeforeEach guard in vue?

this is my router guard :
router.beforeEach(async (to,from,next)=>{
await store.dispatch('GetPermission');
if(to.matched.some(record => record.meta.requireAuth)){
let permissions=store.state.permissions; //getting empty
console.log(permissions);
if(permissions.filter(per => (per.name === 'read_list').length!=0)){
next({
path:'/dashboard/create'
})
}
else{
next()
}
}
// else if(to.matched.some(record => record.meta.requireAuth)){
// if(store.token!=null){
// next({
// path:'/dashboard'
// })
// }
// else{
// next()
// }
// }
else{
next()
}
});
problem is here though i m using await in dispatch method , i m not getting state value of permissions which is initially empty
here is vuex store code :
GetPermission(context){
axios.defaults.headers.common['Authorization']='Bearer ' + context.state.token
axios.get('http://127.0.0.1:8000/api/user').then((response)=>{
console.log(response)
context.commit('Permissions',response.data.permission)
})
//mutation:
Permissions(state,payload){
state.permissions=payload
}
//state
state:{
error:'',
token:localStorage.getItem('token') || null,
permissions:'',
success:'',
isLoggedin:'',
LoggedUser:{}
}
help me to solve it please ??
actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.
Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// Do something here... lets say, a http call using vue-resource
this.$http("/api/something").then(response => {
// http success, call the mutator and change something in state
resolve(response); // Let the calling function know that http is done. You may send some data back
}, error => {
// http failed, let the calling function know that action did not work out
reject(error);
})
})
}
}
Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:
export default {
mounted: function() {
// This component just got created. Lets fetch some data here using an action
this.$store.dispatch("myAction").then(response => {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
})
}
}
Also,you are calling same route when no permission match, in that case it always call your same route and make infinite loop.
Redirect to access denied page if permission denied.

Set up listeners only after permission is verified

I am using react-native-notifications - Version 2.1.7 library to receive notifications in a react-native mobile app. I don't want to set up the notification-related listeners until the user has provided permission to receive notifications.
Q1. The documentation says that it is highly recommended to keep listeners registration at global scope rather than at screen scope. What problems should I expect if I set up listeners at a screen, at which the user is asked to provide permission?
Q2. The device token listener NotificationsAndroid.setRegistrationTokenUpdateListener() does NOT seem to work if it is inside a promise. What am I missing here? Please, see my code below.
// This function is called when the user clicks on the button "Provide permission to receive notifications."
const _requestPermissionNotification = async () => {
let hasPermission = false;
try {
hasPermission = await NotificationsAndroid.isRegisteredForRemoteNotifications();
}
catch (error) {
Alert.alert(
"Notification",
"To utilise the full functionality of this app, Permission to receive notifications is required.",
[{ text: "Ok." }]
);
} // end of: try/catch
if (hasPermission) {
// A. Register Token
// THIS LISTENER DOES NOT SEEM TO WORK UNLESS IT IS SET UP OUTSIDE THE COMPONENT!
NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => {
console.log("PermissionsScreen - setRegistrationTokenUpdateListener - deviceToken:", deviceToken);
});
// B. Pending Notifications
PendingNotifications.getInitialNotification()
.then((notification) => {
console.log("PermissionsScreen - getInitialNotification - notification:", notification);
})
.catch((err) => console.error("getInitialNotifiation failed", err));
// C. Notification Opened
NotificationsAndroid.setNotificationOpenedListener((notification) => {
console.log("PermissionsScreen - setNotificationOpenedListener - :data", notification.getData());
});
// D.a Notification Received
NotificationsAndroid.setNotificationReceivedListener((notification) => {
console.log("PermissionsScreen - setNotificationReceivedListener - data:", notification.getData());
});
// D.b Notification Received "IN FOREGROUND"
NotificationsAndroid.setNotificationReceivedInForegroundListener((notification) => {
console.log("PermissionsScreen - setNotificationReceivedInForegroundListener (foreground)", notification.getData());
});
} // end of: if()
}; // end of: _requestPermissionNotification()
It seems that version 3.1.1 of React-Native-Notifications does not have these limitations anymore.
The following code, which uses the new commands, can be used inside a promise and inside a component.
// Step A.1: Register this app to receive notifications.
Notifications.registerRemoteNotifications();
// Step A.2: Get the device token
Notifications.events().registerRemoteNotificationsRegistered( (event) => {
console.log("deviceToken:", event.deviceToken);
});

How to get notified in React-Native when a device goes offline?

I tried to listen to the isConnected event of NetInfo, but somehow this only fires once, shortly after the app starts. When I deactivate my connection it doesn't fire again.
I tried this in the iOS simulator, so it could be a simulator issue, but I'm not sure.
...
componentWillMount() {
NetInfo.isConnected.addEventListener(
"connectionChange",
this.handleConnectionChange
);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
"connectionChange",
this.handleConnectionChange
);
}
handleConnectionChange = online => this.setState({ online });
...

Can't createAnswer from peer

I'm facing a problem where createAnswer() is not being called.
I'm looking for a way where a new user connects to the website and all other peers get an offer from the new peer and should create an answer. Where is my problem?
function onMessage (topic, event) {
console.log(event);
if(event.session_id == session._session_id)
return;
if(event.sdp) {
console.log(event.sdp.type);
if(event.type == "offer"){
pc.setRemoteDescription(new RTCSessionDescription(event.sdp));
pc.createAnswer(function(offer) {
debugger;
pc.setLocalDescription(offer);
session.publish("http://example.com/webrtc", { session_id: session._session_id ,sdp: offer, type: offer.type});
});
}
}
if(event.candidate)
pc.addIceCandidate(new RTCIceCandidate(event.candidate));
}
For the signalling channel I use Web-sockets an the wamp protocol.
I have deployed the application here,
the source code is available here.