Search code examples
javascriptiosmobile-safariweb-share

Sharing an image using the WebShare API in iOS is failing


I trying to use the WebShare API to share an image in iOS and Android. In Android, my code works perfectly, but in iOS, in some apps like WhatsApp doesn't share the image, it only shares the URL. In a few apps like the email, it's working. I added some code for preventing to share anything else besides the image in iOS like this:

let data = IS_SAFARI ? { files: [], text: '', url: '', title: '' } : { files: [], text: text, url: URL, title: TITLE };

But it still doesn't show the image, it only shares an URL:

const URL = 'https://upload.wikimedia.org/wikipedia/commons/2/27/Map_of_Spain_1490.jpg';
const TYPE = 'image/jpeg';
const EXT = '.jpg';
const TITLE = "yourTitle";
const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

function webshare(text) {

    let navigator;
    navigator = window.navigator;
    let data = IS_SAFARI ? { files: [], text: '', url: '', title: '' } : { files: [], text: text, url: URL, title: TITLE };

    var xhr = new XMLHttpRequest();
    xhr.open('GET', URL, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
        if (xhr.status === 200) {
        var response = xhr.response;
        console.log(response);

        var blob = new File([response], text + EXT, { type: TYPE });
        data.files.push(blob);
        console.log(data);

        if (navigator.canShare && navigator.canShare(data)) {
            navigator.share(data)
            .then(function() {})
            .catch(function(err) {
                console.error('Unsuccessful share ' + err);
            });
        }
        } else {
        console.error('Failed to load ' + URL + ': ' + xhr.status);
        }
    };
    xhr.send();
}
<button onclick="webshare('Map_of_Spain_1490.jpg')">Share</button>

Any idea what am I doing wrong?


Solution

  • I was able to fix it. I had to remove the url, text, and title values from the share like this:

    let data = IS_SAFARI ? { files: [] } : { files: [], text: text, url: URL, title: TITLE };
    

    For any mysterious reason, you cannot share texts and files on iOS at the same time. Then, if I wanted to share a text, I had to do it as a second share like this:

    navigator.share(data)
    .then(function() {
        if (IS_SAFARI) {
            let dataText = { files: [], text: text, url: URL, title: TITLE };
            navigator.share(dataText);
        }                                
    })
    .catch(function(err) {
        console.error('Unsuccessful share ' + err);
    });
    

    It's a very odd and inconvenient bug in iOS. Hopefully, one day Apple will fix these odd bugs.