参考简书:https://www.jianshu.com/p/2d2237ad16d6
第一步 先配置URLtypes (在微信操作完成以后回到原APP)
第二步 直接上代码,然后再解释
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
{
//获取当前的url
let curUrl = navigationAction.request.url
let newcUrUrl = curUrl?.absoluteString ?? ""
// 去除原有的URL回调地址,换成自己的配置
if (newcUrUrl.hasPrefix("https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb")) {
let dic = navigationAction.request.allHTTPHeaderFields
let refer = dic?["Referer"] ?? ""
if refer != "newoa.33iot.com://"{
decisionHandler(WKNavigationActionPolicy.cancel)
if ((curUrl?.absoluteString.contains("redirect_url=")) != nil){
let ary = curUrl?.absoluteString.components(separatedBy: "redirect_url=")
endPayRedirectURL = ary?.last?.removingPercentEncoding ?? ""
}
//对微信的url 进行处理 拼接 App 的标识这里主要是为了
var lastURL = curUrl?.absoluteString.removingPercentEncoding ?? ""
lastURL = lastURL.replacingOccurrences(of: "http://", with: "")
let req = NSMutableURLRequest(url: URL(string: lastURL.getEncodeString)!)
req.httpMethod = "GET"
req.setValue("newoa.33iot.com://", forHTTPHeaderField: "Referer")
self.webView?.load(req as URLRequest)
return;
}
decisionHandler(WKNavigationActionPolicy.allow)
}else{
decisionHandler(WKNavigationActionPolicy.allow)
}
if navigationAction.request.url?.scheme == "tel://" {
//吊起拨打电话
let phoneUrl = url.components(separatedBy: "tel://").last
self.configManager.callSomeOne(phoneUrl!)
}
let scheme = navigationAction.request.url?.scheme ?? ""
if (scheme != "https" && scheme != "http") {
if scheme == "weixin" {
//调用微信
UIApplication.shared.open(navigationAction.request.url!, options: [UIApplication.OpenExternalURLOptionsKey.universalLinksOnly:false]) { flag in }
return
}else if(scheme == "newoa.33iot.com"){
if endPayRedirectURL.length != 0 {
self.webView?.load(URLRequest.init(url: URL(string: endPayRedirectURL)!))
}
}
return
}
}
很多时候h5 跟我的地址 redirect_url后面跟这个的是http 或者https 的这个时候我们就回到不到原APP 来,所以需要把http 去除掉
var lastURL = curUrl?.absoluteString.removingPercentEncoding ?? ""
lastURL = lastURL.replacingOccurrences(of: "http://", with: "")
但是在为了避免 从微信回来显示白色的页面
我们就需要提前把带有http://的链接通过endPayRedirectURL保存下来再通过 scheme的形式判断出来,重新刷新页面
else if(scheme == "newoa.33iot.com"){
if endPayRedirectURL.length != 0 {
self.webView?.load(URLRequest.init(url: URL(string: endPayRedirectURL)!))
}
}
当然也可以
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if url.scheme == "newoa.33iot.com" {
//以通知的形式刷新wkwebview
}
return true
}
如果h5返回的 redirect_url 是不带http:// 就只需要在避免白色的页面添加http
如果再有可能回不来就可能需要配置 apple-app-site-association 文件了 这个网上方法很多我就简单的把我用的贴出来
"appID": "团队ID.bundleID" //中间是以. 连接
"paths":["*","/urlschemes/*"]// 以 /开始 到 /* 结束
切记 一定要检查好格式,不然很难查bug 的