处理这个问题的初衷是:后端返回的用于跳转web页面的URL含有中文,WKWebView在加载包含中文的URL时发生了转义而无法加载只是显示空白页面。需要对包含中文的URL进行编码处理以防止发生转义。
处理方式很简单:
1、编码
- (NSString*)urlEncode:(NSString*)urlString {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)urlString,
(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL,
kCFStringEncodingUTF8));
returnencodedString;
#pragma clang diagnostic pop
}
2、解码
- (NSString*)urlDecode:(NSString*)urlString {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
CFStringEncoding en = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
NSString *decoded = [urlString stringByReplacingOccurrencesOfString:@"+"
withString:@" "];
decoded = (__bridge_transferNSString*)
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
NULL,
(__bridgeCFStringRef)decoded,
CFSTR(""),
en);
returndecoded;
#pragma clang diagnostic pop
}
三、使用方法
对需要编码处理的URL进行编码处理即可,例子如下:
NSString *urlStr = @"https://pay-zto-test.zt-express.com/cashier-static/h5/cashier?systemCode=10007&sceneCode=10025&sign=ed37f0a3a541af5aa11cd273c65f2e44&partnerOrderCode=Z1007876566test&payTypeCode=TC0036&payMethodCode=10002&recipientName=中通快递&platform=txkdg";
NSString*encodeString = [self urlEncode:urlStr];
NSLog(@"编码encodeString===%@",encodeString);
打印结果为:https://pay-zto-test.zt-express.com/cashier-static/h5/cashier?systemCode=10007&sceneCode=10025&sign=ed37f0a3a541af5aa11cd273c65f2e44&partnerOrderCode=Z1007876566test&payTypeCode=TC0036&payMethodCode=10002&recipientName=%E4%B8%AD%E9%80%9A%E5%BF%AB%E9%80%92&platform=txkdg
需要解码回中文的话字节调用解码方法即可。
网友评论