H5和native方法交互经验:
方法一:采用字典匹配模式
//MARK: - WKScriptMessageHandler
extension HomeViewController: WKScriptMessageHandler {
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
//接受传过来的消息从而决定app调用的方法
guard let dict = message.body as? [String: AnyObject] else {
QL1("传入方法有误")
return
}
QL1(dict)
let method: String = dict["method"] as! String
switch method {
case "iOS_MallButtonClick"://JS调用native:找油商城按钮点击
iOS_MallButtonClick()
case "iOS_BuyOrSellButtonClick"://JS调用native:油品买卖按钮点击
iOS_BuyOrSellButtonClick()
case "iOS_PriceButtonClick"://JS调用native:价格变动按钮点击
iOS_PriceButtonClick()
case "iOS_LogisticsButtonClick"://JS调用native:物流配送按钮点击
iOS_LogisticsButtonClick()
case "iOS_MoreOilButtonClick"://更多油品按钮点击
/**
和前端约定好传的字典中键对应的值统一为字符串类型,如果前端传错误了(如传的为Int类型或者Bool类型)的解决办法
法一:Int做空处理,Bool做false处理...代码继续往下走;
法二:进行守护,值错误了则不进往下执行;
*/
let oilType = dict["oilType"] as? String ?? ""
iOS_MoreOilButtonClick(oilType)
case "iOS_OilCellClick"://具体推荐油cell点击
let oilId = dict["oilId"] as? String ?? ""
let allowmax = dict["allowmax"] as? String ?? ""
let allowmin = dict["allowmin"] as? String ?? ""
iOS_OilCellClick(oilId, allowmax: allowmax, allowmin: allowmin)
default:
break
}
}
}
方法二:使用swiftyJSON将web view的message.body转成son,然后再处理
//MARK: - WKScriptMessageHandler
extension HomeViewController: WKScriptMessageHandler {
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
let json = JSON(message.body)
QL1(json)
guard let method = json["method"].string else {//方法名必须为字符串类型
return
}
switch method {
case "iOS_MallButtonClick":// JS调用native:找油商城按钮点击
iOS_MallButtonClick()
case "iOS_BuyOrSellButtonClick":// JS调用native:油品买卖按钮点击
iOS_BuyOrSellButtonClick()
case "iOS_PriceButtonClick":// JS调用native:价格变动按钮点击
iOS_PriceButtonClick()
case "iOS_LogisticsButtonClick":// JS调用native:物流配送按钮点击
iOS_LogisticsButtonClick()
case "iOS_MoreOilButtonClick"://更多油品按钮点击
//和前端约定好传的字典中键对应的值统一为字符串类型,如果前端传错误了(如传的为Int类型或者Bool类型)的解决办法(传值不重要的地方继续往下走,重要的直接守护)
//法一:String做空处理,Int做0处理,Bool做false处理...代码继续往下走;
let oilType = json["oilType"].string ?? ""
/*
//法二:进行守护,值错误了则不进往下执行;
guard let oilType = json["oilType"].string else {
return
}
*/
iOS_MoreOilButtonClick(oilType)
case "iOS_OilCellClick"://具体推荐油cell点击
guard let oilId = json["oilId"].string else {// oilId务必有值,且为字符串类型
return
}
let allowmax = json["allowmax"].string ?? "9999"
let allowmin = json["allowmin"].string ?? "0"
iOS_OilCellClick(oilId, allowmax: allowmax, allowmin: allowmin)
default:
break
}
}
}
网友评论