Share an image with react-native-fbsdk? - facebook

I'm trying to share an image to Facebook in React Native through the react-native-fbsdk package.
I have the following, copied almost completely from the docs, but I can't figure out how to format the imageUrl, I keep getting errors saying the SharingContent is invalid.
What am I doing wrong here?
const sharePhotoContent = {
contentType: 'photo',
photos: [
{
imageUrl: "./local/image/path.png",
userGenerated: false,
caption: "Hello World"
}
]
};
ShareDialog.canShow(sharePhotoContent).then(
function(canShow) {
if (canShow) {
return ShareDialog.show(sharePhotoContent);
}
}
).then(
function(result) {
if (result.isCancelled) {
AlertIOS.alert('Share cancelled');
} else {
AlertIOS.alert('Share success with postId: ' + result.postId);
}
},
function(error) {
AlertIOS.alert('Share fail with error: ' + error);
}
);

You can use the react-native-image-picker https://github.com/marcshilling/react-native-image-picker to get the uri of the image and use it create a SharePhotoContent.
Also note that you need to have the facebook app installed in order to share an image.

This is working fine for me
shareLinkWithShareDialog() {
let shareLinkContent = {
contentType: 'link',
contentUrl: 'https://www.facebook.com/images/fb_icon_325x325.png',
contentDescription: 'Facebook sharing is easy!'
}
ShareDialog.canShow(shareLinkContent).then((canShow) => {
if (canShow) return ShareDialog.show(shareLinkContent);
}
).then((result) => {
if (result.isCancelled) {
alert('Share cancelled');
} else {
alert('Share success with postId: ' + result.postId);
}
},
function(error) {
alert('Share fail with error: ' + error);
}
);
}

Related

Hosting a Forge Autodesk viewer on Github

I've an issue with the Forge viewer I'm developping : Im' trying to host it using Github-page, but it doesn't seem to work correctly.
The issue is on the File tree : when I load the viewer page from the Github pages, the file tree seems stuck on "Loading...". However, it correctly loads when I load the page from localhost.
The code of the File tree :
$(document).ready(function () {
prepareAppBucketTree();
$('#refreshBuckets').click(function () {
$('#appBuckets').jstree(true).refresh();
});
$('#createNewBucket').click(function () {
createNewBucket();
});
$('#createBucketModal').on('shown.bs.modal', function () {
$("#newBucketKey").focus();
})
$('#hiddenUploadField').change(function () {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
var _this = this;
if (_this.files.length == 0) return;
var file = _this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
_this.value = '';
}
});
break;
}
});
});
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
console.log(bucketKey)
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function prepareAppBucketTree() {
$('#appBuckets').jstree({
'core': {
'themes': { "icons": true },
'data': {
"url": '/api/forge/oss/buckets',
"dataType": "json",
'multiple': false,
"data": function (node) {
return { "id": node.id };
}
}
},
'types': {
'default': {
'icon': 'glyphicon glyphicon-question-sign'
},
'#': {
'icon': 'glyphicon glyphicon-cloud'
},
'bucket': {
'icon': 'glyphicon glyphicon-folder-open'
},
'object': {
'icon': 'glyphicon glyphicon-file'
}
},
"plugins": ["types", "state", "sort", "contextmenu"],
contextmenu: { items: autodeskCustomMenu }
}).on('loaded.jstree', function () {
$('#appBuckets').jstree('open_all');
}).bind("activate_node.jstree", function (evt, data) {
if (data != null && data.node != null && data.node.type == 'object') {
// $("#MyViewerDiv").empty();
var urn = data.node.id;
getForgeToken(function (access_token) {
jQuery.ajax({
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn + '/manifest',
headers: { 'Authorization': 'Bearer ' + access_token },
success: function (res) {
if (res.status === 'success') callByUrn('urn:'+urn);
else $("#MyViewerDiv").html('The translation job still running: ' + res.progress + '. Please try again in a moment.');
},
error: function (err) {
var msgButton = 'This file is not translated yet! ' +
'<button class="btn btn-xs btn-info" onclick="translateObject()"><span class="glyphicon glyphicon-eye-open"></span> ' +
'Start translation</button>'
$("#MyViewerDiv").html(msgButton);
}
});
})
}
});
}
function autodeskCustomMenu(autodeskNode) {
var items;
switch (autodeskNode.type) {
case "bucket":
items = {
uploadFile: {
label: "Upload file",
action: function () {
uploadFile();
},
icon: 'glyphicon glyphicon-cloud-upload'
}
};
break;
case "object":
items = {
translateFile: {
label: "Translate",
action: function () {
var treeNode = $('#appBuckets').jstree(true).get_selected(true)[0];
translateObject(treeNode);
},
icon: 'glyphicon glyphicon-eye-open'
}
};
break;
}
return items;
}
function uploadFile() {
$('#hiddenUploadField').click();
}
function translateObject(node) {
$("#MyViewerDiv").empty();
if (node == null) node = $('#appBuckets').jstree(true).get_selected(true)[0];
var bucketKey = node.parents[0];
var objectKey = node.id;
jQuery.post({
url: '/api/forge/modelderivative/jobs',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'objectName': objectKey }),
success: function (res) {
$("#MyViewerDiv").html('Translation started! Please try again in a moment.');
},
});
}
Please note that Github Pages are used for serving static pages without any special server-side logic. Your Forge application requires a server to talk to as well, for example, to obtain a list of buckets for the tree view (by making a request to /api/forge/oss/buckets).
You could potentially host your application's server-side logic on something like Heroku, and then have your static HTML/CSS/JavaScript page on Github talk to that server (for example, https://my-forge-app.herokuapp.com/api/forge/oss/buckets). Just be careful about CORS.

react-native fbsdk is returning email undefined

I m trying to get information through the facebook sdk but so far I am getting only the id and the name of the user. I do have granted the premission but still the email is not popping out like name and id.
I try to console.log(result.email) but i got undefined .
Any help would be appreciated.
Thanks in advance
import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken ,GraphRequest, GraphRequestManager} from 'react-native-fbsdk';
export default class Login extends Component {
render() {
return (
<View>
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
console.log(result.email)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'name,email'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
}

React-native fbsdk get name and email

I'm working in with react-native-fbsdk. I want to get username and email to show up to the user when they're registered to the app in order to create a profile for the app, but no data is shown. How can I get these data and how can I show it in a different screen.
This is my code
import FBSDK from 'react-native-fbsdk'
import { LoginButton,AccessToken,GraphRequest,GraphRequestManager} from 'react-native-fbsdk';
const {
LoginManager,
} = FBSDK;
<LoginButton
readPermissions={['public_profile']}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
const infoRequest = new GraphRequest(
'/me?fields=name,picture',
null,
this._responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start();
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
_responseInfoCallback = (error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
alert('Result Name: ' + result.name);
}
}
}
Thanks friends
I retrieve facebook login while I using firebase.
import this file:
import firebase from "react-native-firebase";
import { AccessToken, LoginManager } from "react-native-fbsdk";
Firebase login code work when I click button:
export const fbLogin = () => {
LoginManager.logInWithReadPermissions(["public_profile", "email"])
.then(result => {
if (result.isCancelled) {
console.log("Login was cancelled");
}
return AccessToken.getCurrentAccessToken();
})
.then(data => {
const credential = firebase.auth.FacebookAuthProvider.credential(
data.accessToken
);
firebase
.auth()
.signInWithCredential(credential)
.then(result => {
Toast.show({
text: "Sucessfully",
position: "top"
});
console.log("Successfully Login", result);
})
.catch(error => {
console.log("Failed", error);
});
})
.catch(err => {
console.log("fail", err);
});
};
I retrive my facebook login data
console.log("Successfully Login", result);
result contains username, email, picture and ..ect credentials
If you don't want to use firebase,
const infoRequest = new GraphRequest(
'/me?fields=name,email,picture.type(large)',
null,
this._responseInfoCallback
);
new GraphRequestManager().addRequest(infoRequest).start();
_responseInfoCallback = (error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
this.setState({ userName: result.name, userEmail: result.email ,userPic:result.picture.data.url});
AsyncStorage.setItem("UserName",this.state.userName);
AsyncStorage.setItem("Email", this.state.userEmail);
AsyncStorage.setItem("UserPic", this.state.userPic);
// SharedPreferences.setItem("UserName", this.state.userName);
// SharedPreferences.setItem("Email", this.state.userEmail);
// SharedPreferences.setItem("UserPic", this.state.userPic);
console.log("Picture"+ this.state.userPic + "Name" + this.state.userName + "Email" + this.state.userEmail);
}
}

react-native-fbsdk get user_birthday and user_location permission doesn't work

Everyone
I am going to get birthday and location from Facebook using react-native-fbsdk.
Here's part of my code:
LoginManager.logInWithReadPermissions(['public_profile', 'user_birthday', 'user_location'])
.then((result) => {
if (result.isCancelled) {
return;
}
AccessToken.getCurrentAccessToken().then((data) => {
console.log(data); // output 1:
const responseInfoCallback = (error, profile) => {
if (error) {
console.log(error);
} else {
console.log(profile); // output 2:
}
};
const accessToken = data.accessToken;
const infoRequest = new GraphRequest(
'/me',
{
accessToken,
parameters: {
fields: {
string: 'name,gender,birthday,location{location}',
},
},
},
responseInfoCallback,
);
new GraphRequestManager().addRequest(infoRequest).start();
});
});
})
.catch(error => console.log(error));
Here's result of output 1 and 2
--------- output 1 -------
{ accessToken: .......,
permissions: [ 'email', 'public_profile' ],
declinedPermissions: [],
applicationID: '968214779983507',
accessTokenSource: undefined,
userID: '161823674419561',
expirationTime: 1515417067593.333,
lastRefreshTime: 1510242607593.949 }
-------output 2--------
{ id: '161823674419561', gender: 'male', name: '....' }
Please help me.
Thanks.
Those permissions only work for users with a role in the App. If you want to make them work for everyone else, you need to go through a review process: https://developers.facebook.com/docs/facebook-login/review

Share custom story with staged image on Facebook using FB.ui no working

I have the following code that stage the canvas image and then create object to share it using FB.ui. Staging the image and create the object are working without problem but the share dialog not displayed. If I replaced the image parameter in create object with an image url it is working.
is there any wrong in my code:
var userAccessToken = $("#user_access_token").val();
var appAccessToken = $("#app_access_token").val();
try {
blob = dataURItoBlob(dataURL);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", userAccessToken);
fd.append("file", blob);
try {
var imageURI;
$.ajax({
url: "https://graph.facebook.com/me/staging_resources",
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data['uri']);
imageURI = data['uri'];
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:true
},
description: ""
}
},
function(response) {
var objectId = response['id'];
FB.ui({
method: 'share_open_graph',
action_type: 'myappnamespace:myaction',
action_properties: JSON.stringify({
myobject:objectId
})
}, function(response){});
}
);
}
});
} catch (e) {
console.log(e);
}
finally I found the solution by changing user_generated parameter from true to false
now the code for creating object looks like below:
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:false
},
description: ""
}
}