Convert the image into base64 string and then send it to shareViaFacebook()
Working code snippet
function shareImage(image) {
getImage(image)
.then(function(base64) {
// check for the required dependencies to avoid runtime JS errors
$window.plugins.socialsharing.shareViaFacebook(
'Add a message here..', // this message would auto-populate as caption
base64, // image to be shared in base64 format
null,
function(result) {
// This is successCallback()
},
function(error) {
// This is errorCallback()
}
);
});
}
function getImage(image) {
var deferred = $q.defer();
getBase64(URI,
function(image) {
deferred.resolve(image);
}
);
return deferred.promise;
}
// There are many ways to get base64 from URI.
// I followed Approach 2 from https://stackoverflow.com/a/20285053/2458543
function getBase64(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
// observation - if below code is removed, then image does not load correctly
if (img.complete || img.complete === undefined) {
img.src = src;
}
}
Some of my important observations while implementing shareViafacebook()
successCallback() and errorCallback() for Android and iOS platforms are quite different
Android
If fb app is NOT installed - errorCallback(error) is invoked where [error = Array(all_apps)]
If fb app is installed
- User not logged in - successCallback(result) is invoked where [result = "OK"]
- User logged in - successCallback(result) is invoked where [result = "OK"]
This does not wait for successfully sharing the image and returns as soon as the facebook app opens
- Cancelled (by user) - Do Nothing
iOS
If fb app is NOT installed - errorCallback(error) is invoked where [error = "cancelled"]
If fb app is installed
- User not logged in - errorCallback(error) is invoked where [error = "cancelled"]
- User logged in - successCallback(result) is invoked where [result = true]
This waits for successfully sharing the image and returns on completing the share action
- Cancelled (by user) - errorCallback(error) is invoked where [error = "cancelled"]