WKWebView加载带#的url,无法访问
2019-11-11 本文已影响0人
WMSmile
今天在做项目中,遇到用WKWebView加载url,无法访问。最后发现是url里面的#被编码成%23导致无法访问
https://127.0.0.1/#/?name=华为
编码之后:
https://127.0.0.1/%23/?name=%E5%8D%8E%E4%B8%BA
当 # 号被编译成 %23 之后无法访问
解决办法:禁止 **# ** 号编译成 **%23 **
OC
- (NSString *)WM_FUNC_urlEncode:(NSString *)urlStr{
NSMutableCharacterSet *set = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[set addCharactersInString:@"#"];
return [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
}
swift 4.0
func WM_FUNC_urlEncode(_ urlStr:String) -> String {
if urlStr.isEmpty {
return ""
}
var charSet = CharacterSet.urlQueryAllowed
charSet.insert(charactersIn: "#")
let encodingURLStr = urlStr.addingPercentEncoding(withAllowedCharacters: charSet)
return encodingURLStr ?? ""
}
下面模仿oc写法: CharacterSet转换NSMutableCharacterSet来操作
func WM_FUNC_urlEncode(_ urlStr:String) -> String {
if urlStr.isEmpty {
return ""
}
let charSet = CharacterSet.urlQueryAllowed as NSCharacterSet
let mutSet = charSet.mutableCopy() as! NSMutableCharacterSet
mutSet.addCharacters(in: "#")
let encodingURLStr = urlStr.addingPercentEncoding(withAllowedCharacters: mutSet as CharacterSet)
return encodingURLStr ?? ""
}
func WM_FUNC_urlEncode(_ urlStr:String) -> String {
if urlStr.isEmpty {
return ""
}
let charSet = NSMutableCharacterSet()
charSet.formUnion(with: CharacterSet.urlQueryAllowed)
charSet.addCharacters(in: "#")
let encodingURLStr = urlStr.addingPercentEncoding(withAllowedCharacters: charSet as CharacterSet)
return encodingURLStr ?? ""
}