Share a URL as post in Facebook App from React-Native App - react-native

I have a React-native app, from which I want share my website's URL in a Facebook post.
My current code is :
import Share from "react-native-share";
const shareToFacebook = async () => {
const shareOptions = {
social: Share.Social.FACEBOOK,
message: "Test message",
url: "https://example.com/",
};
try {
const ShareResponse = await Share.shareSingle(shareOptions);
console.log(ShareResponse);
} catch (error) {
console.log("Error =>", error);
}
};
but this solution ,opens Facebook in the browser. Is there any way to open the actual Facebook app ?

Facebook offers an SDK for sharing posts, you can use that SDK with react-native-fbsdk-next library. It shows an in-app modal. I think showing an in-app modal is better than the open the Facebook app or open a browser because some people do not have Facebook on their phones.
You can test the share function before installing the library, follow below steps:
# clone the react-native-fbsdk-next
git clone https://github.com/thebergamo/react-native-fbsdk-next.git
# go to the test project
cd RNFBSDKExample
# install dependencies
npm install
# run the project
npm run android
Example code (from README page):
// ...
import { ShareDialog } from 'react-native-fbsdk-next';
// ...
// Build up a shareable link.
const shareLinkContent = {
contentType: 'link',
contentUrl: "https://facebook.com",
contentDescription: 'Wow, check out this great site!',
};
// ...
// Share the link using the share dialog.
shareLinkWithShareDialog() {
var tmp = this;
ShareDialog.canShow(this.state.shareLinkContent).then(
function(canShow) {
if (canShow) {
return ShareDialog.show(tmp.state.shareLinkContent);
}
}
).then(
function(result) {
if (result.isCancelled) {
console.log('Share cancelled');
} else {
console.log('Share success with postId: '
+ result.postId);
}
},
function(error) {
console.log('Share fail with error: ' + error);
}
);
}
Read more about Facebook Sharing Feature.

Related

Expo facebook login fails: error : server with the specified hostname could not be found?

UPDATE: it works in the IOS simulator, but only doesnt work in my expo go app.
I have an expo react native managed app. I tried to implement the facebook login but I always get the following error:
my code (there should not be problems with it, its just the sample code from expo)
const AuthScreen = () => {
import * as Facebook from 'expo-facebook';
const loginWithFacebook = async () => {
try {
await Facebook.initializeAsync({
appId: '<MYAPPID>',
});
const {type, token, expirationDate, permissions, declinedPermissions} =
await Facebook.logInWithReadPermissionsAsync({
permissions: ['public_profile'],
});
if (type === 'success') {
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
} else {
// type === 'cancel'
}
} catch ({message}) {
alert(`Facebook Login Error: ${message}`);
}
};
return (
<FontAwesome.Button name="facebook" onPress={loginWithFacebook}>Login With Facebook</FontAwesome.Button>
)
};
What I did so when registering my app:
in facebook developers I created my app 'rainy'.
In settings/basic I added IOS and Android.
a. in IOS I only added host.exp.Exponent as the Bundle ID
b. In android I only added the hash key: rRW++LUjmZZ+58EbN5DVhGAnkX4= (I couldnt find that hash on expo docs anymore but found it elsewhere and it should be up to date)
in app.json I added infoPlist with properties to ios as following:
...
"ios": {
"supportsTablet": true,
"infoPlist": {
"facebookScheme": "fb<MYAPPID>",
"facebookAppId": "<MYAPPID>",
"FacebookClientToken": "abcxxxxx", //got it from Settings > Advanced > Client Token
"facebookDisplayName": "rainy",
"facebookAutoLogAppEventsEnabled": false,
"facebookAdvertiserIDCollectionEnabled": false
}
},
...
I wasnt sure but also (after getting the error) tried to add to Valid OAuth Redirect URIs the following: https://auth.expo.io/#/rainy. not sure if even needed but the error is still the same
Also I expo installed expo-facebook.
Did I miss any step or did something wrong? Thank you!!

expo-camera: Error: Permissions module is null

I have an error in console after to install expo-camera.
expo install expo-camera
add permission in android manifest
add module expo camera in maven
allprojects {
repositories {
// * Your other repositories here *
// * Add a new maven block after other repositories / blocks *
maven {
// expo-camera bundles a custom com.google.android:cameraview
url "$rootDir/../node_modules/expo-camera/android/maven"
}
}
}
start the protect
click on the button to show camera ... error in log
Error: Permissions module is null.
Permission:
<uses-permission android:name="android.permission.CAMERA" />
update 1 :
I test with this code example to check my permission
https://reactnative.dev/docs/permissionsandroid
my example function
// state local
const [hasPermission, setHasPermission] = useState(null);
// function
const requestCameraPermission = async () => {
console.log('requestCameraPermission')
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: "Cool Photo App Camera Permission",
message:
"Cool Photo App needs access to your camera " +
"so you can take awesome pictures.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
setHasPermission(true)
console.log("You can use the camera");
} else {
console.log("Camera permission denied");
setHasPermission(false)
}
} catch (err) {
console.warn(err);
}
};
// result of requestCameraPermission : You can use the camera
// Error : Attempt to invoke interface method 'boolan expo.modules.interfaces.permission.Permission.hasGrantedPermissions(java.lang.string[]) on a null object reference
I make something wrong ?
thanks for help
If you did just these steps, you have to do more things to make it works on Android device.
Github page says:
Adjust the android/build.gradle to add a new maven block after all other repositories as described below:
allprojects {
repositories {
// * Your other repositories here *
// * Add a new maven block after other repositories / blocks *
maven {
// expo-camera bundles a custom com.google.android:cameraview
url "$rootDir/../node_modules/expo-camera/android/maven"
}
}
}
But before do that, you should:
For bare React Native projects, you must ensure that you have installed and configured the react-native-unimodules package before continuing.

React-Native: Can't receive expo push notification on stand alone app

This is ss from standalone app, its gettings expo token but for some reason it wont show notifications
I can't receive push notification on my standalone apps and if someone else used the app from expo (not my phone) then he won't receive it either,
For some reason only i receive it ..that too on expo client and if i install the apk on my phone, then i get the error....
In these all situations the error is same,
{
"data": {
"status": "error",
"message": "SNS failed to send the notification (reason: EndpointDisabled, status code: 400).",
"details": {
"error": "DeviceNotRegistered",
"sns": {
"statusCode": 400,
"reason": "EndpointDisabled",
"__message": "Endpoint is disabled"
}
}
}
}
my notification js
import { Permissions, Notifications } from 'expo';
import { AsyncStorage } from 'react-native';
import axios from 'axios';
import {
IUSTCONNECT_URL
} from '../actions/types';
const server = IUSTCONNECT_URL;
export default async function registerForPushNotificationsAsync() {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
// only ask if permissions have not already been determined, because
// iOS won't necessarily prompt the user a second time.
if (existingStatus !== 'granted') {
// Android remote notification permissions are granted during the app
// install, so this will only ask on iOS
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
// Stop here if the user did not grant permissions
if (finalStatus !== 'granted') {
return;
}
// Get the token that uniquely identifies this device
let token = await Notifications.getExpoPushTokenAsync();
console.log(token);
await AsyncStorage.setItem('notificationToken', token);
const adminFlag = await AsyncStorage.getItem('admin');
try {
const { data } = await axios.post(`${server}/admin/app_bridge/user.php`, {
job: 'updateExpoToken',
admin: adminFlag,
token: token
});
if(data.trim() === 'success') {
console.log('expo push notification token sent:');
} else {
console.log('error sending notification token:');
console.log(data);
}
} catch (e) {
console.log(e);
}
}
and i am calling registerForPushNotificationsAsync() on my child tab,
Everything works well for my expo app...rest it doesn't...
Any help?
The issue is with the device. you can see in error DeviceNotRegistered.
see expo docs here.
DeviceNotRegistered: the device cannot receive push notifications
anymore and you should stop sending messages to the given Expo push
token.
The problem is that in docs no information why this error is happening. Try with some other device's.
if you develop with firebase you need update your token, the steps are:
1 in your page of project firebase, select option setting.
2 navigate to option project settings.
3 select option cloud messasging.
4 on credetial of project copy the token.
5. in your terminal in root directory of project type:
expo push:android:upload --api-key <your token>
for more information visit
enter link description here
try send push notification Manually
enter link description here
i'm working with sdk 37.0.0

How to download a file with React Native?

I am building an app with React Native, for Android and iOS. I am trying to let the user download a PDF file when clicking on a button.
react-native-file-download does not support Android
react-native-fs does nothing when I trigger downloadFile (nothing shows up on the notification bar), and I am not able to find the file after that. I added android.permission.WRITE_EXTERNAL_STORAGE to the Android Manifest file. I double-checked that the file I am trying to download exists (when it does not, the library throws an error)
I do not find other solutions for this problem. I have found libraries for viewing a PDF, but I would like to let the user download the PDF.
Just implemented the download feature an hour ago :p
Follow these steps:
a) npm install rn-fetch-blob
b) follow the installation instructions.
b2) if you want to manually install the package without using rnpm, go to their wiki.
c) Finally, that's how I made it possible to download files within my app:
const { config, fs } = RNFetchBlob
let PictureDir = fs.dirs.PictureDir // this is the pictures directory. You can check the available directories in the wiki.
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
notification : false,
path: PictureDir + "/me_"+Math.floor(date.getTime() + date.getSeconds() / 2), // this is the path where your downloaded file will live in
description : 'Downloading image.'
}
}
config(options).fetch('GET', "http://www.example.com/example.pdf").then((res) => {
// do some magic here
})
If you're using Expo, react-native-fetch-blob won't work. Use FileSystem.
Here's a working example:
const { uri: localUri } = await FileSystem.downloadAsync(remoteUri, FileSystem.documentDirectory + 'name.ext');
Now you have localUri with the path to the downloaded file. Feel free to set your own filename instead of name.ext.
I Followed the solution from Jonathan Simonney, above on this post. But I had to change it a little:
const { config, fs } = RNFetchBlob;
const date = new Date();
const { DownloadDir } = fs.dirs; // You can check the available directories in the wiki.
const options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true, // true will use native manager and be shown on notification bar.
notification: true,
path: `${DownloadDir}/me_${Math.floor(date.getTime() + date.getSeconds() / 2)}.pdf`,
description: 'Downloading.',
},
};
config(options).fetch('GET', 'http://www.africau.edu/images/default/sample.pdf').then((res) => {
console.log('do some magic in here');
});
GetItem_downloadbtn = (item, itemname) => {
console.log("fiel url comiugn jdd " + item);
console.log("item name checkoing " + itemname);
const android = RNFetchBlob.android;
const filename = itemname;
const filepath = RNFetchBlob.fs.dirs.DownloadDir + '/foldernamae/' + filename;
const downloadAppUrl = item;
RNFetchBlob.config({
addAndroidDownloads: {
useDownloadManager: true,
title: 'great, download success',
description:'an apk that will be download',
mime: 'application/vnd.android.package-archive',
// mime: 'image/jpeg',
// mediaScannable: true,
notification: true,
path: filepath
}
})
.fetch('GET', downloadAppUrl)
.then((res) => {
// console.log('res.path ', res.path());
alert('res.path ', res.path());
android.actionViewIntent(res.path(), 'application/vnd.android.package-archive');
})
.catch((err) => {
alert('download error, err is', JSON.stringify(err));
});
}
I had the same issue, got it working using Expo WebBrowser Module
// install module
npm install react-native-webview
// import the module
import * as WebBrowser from 'expo-web-browser';
// then in your function you can call this function
await WebBrowser.openBrowserAsync(file_ur);
it will open preview of the file and then user can download using share button.

MobileFirst and Ionic Push notification callback

I have an Ionic project and I added a push notification callback handler as explained in official documentation (my expectation is to have some alert when inside the app and a notification arrive), but it is never invoked.
WL.Client.Push.registerEventSourceCallback(
"myPush",
"PushAdapter",
"PushEventSource",
pushNotificationReceived);
Here the question is where I have to place the pushNotificationReceived function to be called ? I try in index.js and inside the controller as a function, but I do not have success.
Thank for help
Have you reviewed the sample application for push notifications?.
The sample demonstrates implementation of push notifications APIs. https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/notifications/push-notifications-overview/push-notifications-in-hybrid-applications/event-source-notifications-in-hybrid-applications/
See the supplied main.js file: https://github.com/MobileFirst-Platform-Developer-Center/EventSourceNotifications/blob/release71/apps/HybridEventSource/common/js/main.js
You have to include callback function in ionic inside the app.js file after "Successfully connected with mobile first server".
WLAuthorizationManager.obtainAccessToken().then(
function (response) {
//alert("successfully obtained a token from the server");
MFPPush.initialize (
function(successResponse) {
//alert("Successfully intialized");
MFPPush.registerNotificationsCallback(notificationReceived);
},
function(failureResponse) {
console.log("Failed to initialize");
}
);
MFPPush.isPushSupported (
function(successResponse) {
//alert("Push Supported: " + successResponse);
},
function(failureResponse) {
console.log("Failed to get push support status");
}
);
MFPPush.registerDevice(
function(successResponse) {
//alert("Successfully registered");
},
function(failureResponse) {
console.log("Failed to register");
}
);
function notificationReceived(message) {
alert(JSON.stringify(message.alert));
}
},
function(response) {
//alert("res"+JSON.stringify(response));
console.log("Unable to obtain a token from the server: " + JSON.stringify(response));
if(JSON.stringify(response.status) == 403){
console.log("The Application is disabled on this Device");
ionic.Platform.exitApp();
}
}
);