我尝试使用 WebShare API 在 iOS 和 Android 中共享图像。在 Android 中,我的代码运行完美,但在 iOS 中,在 WhatsApp 等某些应用程序中不共享图像,它仅共享 URL。在电子邮件等一些应用程序中,它可以正常工作。我添加了一些代码来防止在 iOS 中共享除图像之外的任何其他内容,如下所示:
let data = IS_SAFARI ? { files: [], text: '', url: '', title: '' } : { files: [], text: text, url: URL, title: TITLE };
但是还是不显示图片,只分享一个网址:
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>
知道我做错了什么吗?
我能够修复它。我不得不从共享中删除
url
、text
和 title
值,如下所示:
let data = IS_SAFARI ? { files: [] } : { files: [], text: text, url: URL, title: TITLE };
出于任何神秘原因,您不能同时在 iOS 上共享文本和文件。然后,如果我想分享一个文本,我必须像这样作为第二个分享来做:
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);
});
这是 iOS 中一个非常奇怪和不便的错误。希望有一天 Apple 会修复这些奇怪的错误。
谢谢你! 第二个分享的 .then() 部分对你有用吗?它似乎在我的测试设备上被忽略了......