需求:安卓和IOS开发的混合app。前端使用vue,vant2,安卓使用java,ios使用的object-c。实现效果:点击按钮,下载PDF附件,app跳转到手机外部浏览器,下载附件......
1,安卓端代码:
public static void openPDFInBrowser(Context context, String url) {
Uri uri \= Uri.parse(url);
Intent intent \= new Intent(Intent.ACTION\_VIEW, uri);
intent.putExtra(Browser.EXTRA\_APPLICATION\_ID, context.getPackageName());
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w("error", "Activity was not found for intent, " + intent.toString());
}
}
2,IOS端代码:
\[\[UIApplication sharedApplication\]openURL:URL options:@{} completionHandler:^(BOOL success) {
}\];
函数异步执行,在主队列中调用 completionHandler 中的回调。
参数:
openURL:打开的网址
options:用来校验url和applicationConfigure是否配置正确,是否可用。
如果校验为不可用,completionHandler的回调success为NO。
唯一可用@{UIApplicationOpenURLOptionUniversalLinksOnly:@YES}。
不需要就用@{}为置空,不能直接置nil。
置空将不会校验,completionHandler的回调success恒为YES。
ompletionHandler:如不需要可置nil
3,前端代码使用桥接:
\_download(){
const that \= this;
const {voucherNo,unionid,custId} \= this;
const baseUrl \= config.BASE\_API;
const url \= \`/api/wx/down/voucherDetailByB001?voucherId=${voucherNo}&unionId=${unionid}\`;
const downUrl \= baseUrl + url;
this.isLoading = true;
this.loadingText = "下载中";
this.$JQAPI('saveFile', {
param: {url: downUrl, suffix: 'pdf' },
successCallBack: function (res) {
that.isLoading \= false;
const result \= JSON.parse(res);
console.log(result);
if (result && result.code == 200) {
const data \= result.data;
console.log(data);
Toast({message:\`文件已保存至${data}文件夹\`,position: 'bottom',duration: 5000});
} else {
that.$toast(result.msg);
}
},
failedCallBack: function (err) {
console.log(err)
that.$toast(err);
that.isLoading \= false;
}
});
注意:后端代码返回流,不能设置content-type:application/x-msdownload,否则IOS下载的附件会带上.exe