最近在完成公司项目时遇到了一个需求,要求一键复制广告的文本和广告内的所有图片
解决方法如下:
第一步:在点击按钮处,点击时传参,分别时双向绑定的文本内容,图片视频地址,
<button class="relay" @click="copy(adetails.content,adetails.url,adetails.type)">一键转发朋友圈</button>
第二步定义方法:接受三个参数,同时根据type的值进行判断,type=2时调用保存图片,(注意:type为2是指url地址内容是图片,type为3是指url地址内容是视频。,
//转发的一键复制文本内容和下载图片到手机相册
copy(content, url, type,id) {
console.log(id)
let thit = this
let imageArr = url
uni.setClipboardData({
data: content,
showToast: false,
success: function() {
// console.log('success');
thit.forwardAd(id)
}
});
if (type == 2) {
for (let i = 0; i < imageArr.length; i++) {
thit.saveImage(imageArr[i], i, imageArr.length,type)
}
} else {
thit.saveImage(imageArr,type)
}
},
第三步:下载图片和下载视频的方法
// 向用户发起保存图片授权请求
saveImage(url, i, long,type) {
let that = this;
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
// 已授权
if(type==2){
that.download(url, i, long);
}else{
that.downloadvideo(url)
}
},
fail: () => {
// 拒绝授权,获取当前设置
uni.getSetting({
success: (result) => {
if (!result.authSetting['scope.writePhotosAlbum']) {
that.isAuth()
}
}
});
}
})
},
//前期未授权提示
isAuth() {
uni.showModal({
content: '由于您还没有允许保存图片到您相册里,无法进行保存,请点击确定允许授权',
success: (res) => {
if (res.confirm) {
uni.openSetting({
success: (result) => {
console.log(result.authSetting);
}
});
}
}
});
},
//下载图片
download(url, i, long) {
console.log(url, i, long)
let num_long = long - 1
const downloadTask = uni.downloadFile({
url: url,
success: (res) => {
console.log(res)
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
})
if (i == num_long) {
uni.showModal({
title: '内容已复制,图片已下载至相册',
showCancel:false,
content: '请立即去朋友圈转发,转发完成后,截图到“我的任务”中提交审核,审核通过后即得赏金',
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
}
}
})
},
//下载视频
downloadvideo(url) {
console.log(url)
uni.showLoading();
const downloadTask = uni.downloadFile({
url: url[0],
success: (res) => {
console.log(res)
uni.saveVideoToPhotosAlbum({
filePath: res.tempFilePath,
})
}
});
downloadTask.onProgressUpdate(res => {
// console.log('下载进度' + res.progress);
// console.log('已经下载的数据长度' + res.totalBytesWritten);
// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite)
if (res.progress == 100) {
uni.hideLoading();
uni.showModal({
title: '内容已复制,视频已下载至相册',
showCancel:false,
content: '请立即去朋友圈转发,转发完成后,截图到“我的任务”中提交审核,审核通过后即得赏金',
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
}
})
},