0

I am a hybrid (Cordova) mobile app developer and my requirement is to share GIF images to various social media platforms. I have written a function that converts my image into Base64 data url. Mostly it converts the image and makes the share smooth but sometimes, it fails to share the image on click of share button. And sometimes it does not open the share window. I suspect it is taking a bit long to convert the image. Here is my sample code:

function convertFileToDataURLviaFileReader(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function () {
        var reader = new FileReader();
        reader.onloadend = function () {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);  
    xhr.send();
}

And this is how the function is being called:

//The below function will be called on click of share buttons

function showSnackBar(e) {
    imgSource = null;
    selectedImgId = null;
    imgDataURL = null;
    var x = document.getElementById("snackbar");
    imgSource = e.target.currentSrc;
    selectedImgId = e.target.id;
    x.className = "show";
    setTimeout(function () {
        x.className = x.className.replace("show", "");
    }, 3000);
    //calling function to Convert ImageURL to DataURL
    convertFileToDataURLviaFileReader(imgSource, function (base64Img) {
        imgDataURL = base64Img;
    });
    $("#btnShare").click(function (e) {
        if(imgDataURL != null) {
            window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null) 
        }
    })
};
dakab
  • 5,379
  • 9
  • 43
  • 67
Arpita Dutta
  • 291
  • 7
  • 19

1 Answers1

0

Try setting a variable if the conversion isn't done yet, then launching the share dialog once the conversion is complete (notice the use of the openShare variable below):

function showSnackBar(e) {
    imgSource = null;
    selectedImgId = null;
    imgDataURL = null;
    var x = document.getElementById("snackbar");
    imgSource = e.target.currentSrc;
    selectedImgId = e.target.id;
    x.className = "show";
    setTimeout(function () {
        x.className = x.className.replace("show", "");
    }, 3000);

    var openShare = false;
    //calling function to Convert ImageURL to DataURL
    convertFileToDataURLviaFileReader(imgSource, function (base64Img) {
        imgDataURL = base64Img;
        if(openShare){
            openShare = false;
            window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null); 
        }
    });

    $("#btnShare").click(function (e){
        if(imgDataURL != null) {
            window.plugins.socialsharing.share(null, 'Android filename', imgDataURL, null) 
        }else{
            openShare = true;
        }
    });
};
Femi
  • 64,273
  • 8
  • 118
  • 148