Can't receive push notifications using Ionic Cloud on iOS - swift

I'm using ionic's cloud push notification service for both android and iOS, along with phonegap-plugin-push. Since i'm using my own server-side authentcation and not ionic's, I have it configured so that a user's authentication token is registered depending on whether or not they're logged in, and saved when they log in (unregistered when they log out).
App.module:
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'APP_ID',
},
'push': {
'sender_id': 'SENDER_ID',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true,
},
'android': {
'iconColor': '#343434'
}
}
}
};
instead of making push a provider in app module, I made an injectable service that can be used across components. The main app component subscribes to the notifications, while my login and logout components tell it whether or not to register and save them.
export class NotificationService{
token: PushToken;
registered: boolean;
constructor(public push: Push){
}
checkLogin(status){
if(!status){
this.push.register().then((pushT: PushToken) => {
this.token = pushT;
console.log('token saved:'+ this.token);
});
}
}
saveToken(){
this.push.saveToken(this.token);
console.log('token saved');
this.registered = true;
this.startListening();
}
deleteToken(status){
if(status){
this.push.unregister().then(function(){
console.log('token deleted');
return true;
})
}
}
startListening(){
if(this.registered){
return this.push.rx.notification()
.subscribe((msg) => {
alert(msg.title + ': ' + msg.text);
});
}}
getToken(){
return this.token.token;
}
}
I have my sender ID for GCM configured in config.xml and ionic cloud, and my APNS certificate is saved in ionic cloud. So far this works perfectly on android. On iOS it registers the token and saves to the database, but testing on Ionic cloud my iPhone doesn't receive any notifications. Any thoughts?

Related

Firebase auth web SDK not working on Ionic iOS?

My issue is the login with the email and password function works fine on android but on iOS, the promise is never returned ( nor failed ) when correct credentials are provided but it fails if I provide incorrect credentials. The login works on iOS with live reload simulating on an iOS device, but when installed with test-flight or via xCode promise is never returned nor rejected.
How can I debug it further or know what the underlying issue is?
onSubmit: async (values) => {
try {
const auth = getAuth(firebaseApp);
auth.setPersistence(browserSessionPersistence);
// Never called on IOS
auth.onAuthStateChanged(() => {
console.log('I am here', auth.currentUser);
if (auth.currentUser) {
updateIsAuthenticated(true);
}
});
const userCred = await signInWithEmailAndPassword(auth, values.email, values.password);
//Never runs
console.log('After Success', userCred);
} catch (error) {
// Runs when provided with false credentials
setError('Error: Authentication failed');
console.error('An error Occurred');
} finally {
console.log('Running Finally');
}
},
});

Keycloak Capacitor Adapter - Auth Redirect Problem

We are using Ionic Vue (5.4.0 - Vue3) with Capacitor and Keycloak as the Auth Provider. We have implemented the https://www.npmjs.com/package/keycloak-ionic Package which provides the Capacitor Adapter. We have set up the required deeplinks for both platforms and they are working. The app should authenticate the user in the system browser (capacitor-native adapter), save the tokens and reuse these tokens on the next appstart. It's working on android. On iOS the first startup is working but if i restart (terminating and starting again) i only see a blank screen. It's not redirecting into the secured content or showing the keycloak login page. I found out that the Safari Browser with the keycloak login is opened in the background. If i close this browser tab and start the app it's working by redirecting me to the keycloak login page.
May the browser with the opened keycloak instance be the problem?
I also tried the same with inappbrowster (capacitor adapter). The first start is working there also. If i restart the app the custom tab is opening the redirect url page without redirecting me to the secured content or to the keycloak login page.
Code Sample:
App.addListener('appUrlOpen', function (data: any) {
const slug = data.url.split('/kc1').pop()
// We only push to the route if there is a slug present
if (slug) {
router.push({ name: 'Overview' })
}
})
// init authentication
const initKeycloak = async () => {
const cachedKeycloak = new CacheUtil('keycloak')
const cachedKeycloakAccessToken = await cachedKeycloak.get('accessToken')
const cachedKeycloakRefreshToken = await cachedKeycloak.get('refreshToken')
const initOptions = { url: process.env.VUE_APP_AUTH_URL + '/auth', realm: 'mp', clientId: 'mobile', checkLoginIframe: false, onLoad: 'login-required', token: cachedKeycloakAccessToken, refreshToken: cachedKeycloakRefreshToken }
const keycloak = KeycloakIonic(initOptions)
keycloak.init({
adapter: 'capacitor-native',
pkceMethod:'S256',
onLoad: initOptions.onLoad as any,
redirectUri: process.env.VUE_APP_REDIRECT_URI
}).then((auth: any) => {
// auth and create app
if (!auth) {
console.log(auth)
} else {
const app = createApp(VueApp)
.use(IonicVue)
.use(router)
.use(store)
router.isReady().then(() => {
app.mount('#app')
})
}
}).catch((e: Error) => {
console.log('auth failed: ', e)
})
keycloak.onAuthSuccess = () => {
console.log('authenticated!')
// save tokens to device storage
cachedKeycloak.set('accessToken', keycloak.token)
cachedKeycloak.set('refreshToken', keycloak.refreshToken)
}
}
initKeycloak()

How to use Pushwoosh in Ionic 5 project with capacitor

Hi everyone I am migrating an app from ionic 1 to ionic 5 and I need to integrate the pushwoosh notification service, my project was started not using cordova, instead I use capacitor and I can't find information about how to integrate this service to an ionic 5 application.
Please, we already know that you can use cordova but when using the cordova plugin add pushwoosh-cordova-plugin#8.0.0 it gives you the following message:
Current working directory is not a Cordova-based project.
because as I said before it is a capacitor project not a cordovan project, Btw I already use ionic integrations enable cordova
So... if anyone can help us, It would be very helpful.
OK guys after many hours trying to integrate Pushwoosh into an ionic 5 application for me it was impossible,
If you set everything up correctly, the following will happen:
Your app will connect to Pushwoosh correctly
Your app will correctly register your device in pushwoosh
But your app will not listen to the listeners offered by the official Pushwoosh documentation
document.addEventListener('push-receive',
function (event) {
var message = (<any>event).notification.message;
var userData = (<any>event).notification.userdata;
alert("Push message received: " + message);
console.info(JSON.stringify((<any>event).notification));
//dump custom data to the console if it exists
if (typeof (userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
}
);
This does not work in an ionic 5 app 👆🏽
This does work:
import { Component, OnInit } from '#angular/core';
import {
Plugins,
PushNotification,
PushNotificationToken,
PushNotificationActionPerformed,
} from '#capacitor/core';
const { PushNotifications } = Plugins;
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
ngOnInit() {
console.log('Initializing HomePage');
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
PushNotifications.requestPermission().then(result => {
if (result.granted) {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener(
'registration',
(token: PushNotificationToken) => {
alert('Push registration success, token: ' + token.value);
},
);
PushNotifications.addListener('registrationError', (error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotification) => {
alert('Push received: ' + JSON.stringify(notification));
},
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
alert('Push action performed: ' + JSON.stringify(notification));
},
);
}
}
I tried to combine Pushwoosh with the capacitor but the tokens of the devices that are generated are different so I still didn't get my notifications.
At the end of the day and after many hours and days of work I have no other option than to use firebase and now everything is going much better.

Handling Facebook/Google login with ngCordovaOauth in Ionic + Firebase

I'm trying to implement Firebase authentication with angularfire signInWithCredential method for my Ionic app. As I'm using Firebase 3.x SDK, the methods signInWithRedirect and signInWithPopup are not yet supported on mobile devices. Thus I'm using the plugin ngCordovaOauth.
var ref = firebase.database().ref().child("users");
$scope.users = $firebaseArray(ref);
$cordovaOauth.facebook("//removed_client_id", [ "public_profile", "email"]).then(function(result) {
var credentials = firebase.auth.FacebookAuthProvider.credential(result.access_token);
$scope.authObj.$signInWithCredential(credentials).then(function(authData) {
var existUser = $scope.users.$getRecord(authData.uid);
if(existUser == null){
$scope.user = {
uid: authData.uid,
displayName: authData.displayName,
avatar: authData.photoURL,
email: authData.email,
contact: "0000000000",
provider: "facebook"
}
firebase.database().ref("users/" + authData.uid).set($scope.user);
}
$rootScope.result = authData;
$state.go("menu.home");
}, function(error) {
console.error("ERROR: " + error);
});
}, function(error) {
console.log("ERROR: " + error);
});
The problem that I'm facing is I have no idea what the structure of 'authdata' is as I couldn't find any documentation for the same. With sigInWithPopup, firebase returns 'result' object; contents of which can be accessed like 'result.user.uid', 'result.user.displayName' or 'result.user.email'. How can I achieve the same here as I'm trying to store the user profile when he logs in for the first time? Any help? I'm testing on android device. Thank you!
signInWithCredential returns a promise that resolves with a firebase.User same as signInWithEmailAndPassword and all other sign in apis.
Check the docs for more info on firebase.User:
https://firebase.google.com/docs/reference/js/firebase.User

Getting user app token using react-native facebook SDK

I've gotten facebook login working using the new https://github.com/facebook/react-native-fbsdk, however I can't seem to get the user token which is usually returned in the response. Anyone found a way to get this information? The other SDK's https://github.com/magus/react-native-facebook-login returns it on the login request but the new FB sdk doesn't, and the documentation on the github page doesn't mention it anywhere.
Found the answer after some more digging. You need to use the fbsdkcore to access the user token. Heres how you use it.
var FBSDKCore = require('react-native-fbsdkcore');
var {
FBSDKAccessToken,
} = FBSDKCore;
var Login = React.createClass({
render: function() {
return (
<View>
<FBSDKLoginButton
onLoginFinished={(error, result) => {
if (error) {
alert('Error logging in.');
} else {
if (result.isCanceled) {
alert('Login cancelled.');
} else {
FBSDKAccessToken.getCurrentAccessToken((token) => {
console.log(token.tokenString);
})
}
}
}}
onLogoutFinished={() => console.log('Logged out.')}
readPermissions={[]}
publishPermissions={['publish_actions']}/>
</View>
);
}
});
You don't need a third party module (react-native-fbsdkcore)
The package (react-native-fbsdk) has instructions on it's Github page: https://github.com/facebook/react-native-fbsdk#usage
After you've logged the user in, you can fetch the access credentials as follows:
import { AccessToken } from 'react-native-fbsdk';
AccessToken.getCurrentAccessToken().then(data => {
console.log(data.accessToken.toString())
})