處理這個問題的初衷是:后端返回的用于跳轉(zhuǎn)web頁面的URL含有中文绞呈,WKWebView在加載包含中文的URL時發(fā)生了轉(zhuǎn)義而無法加載只是顯示空白頁面纱意。需要對包含中文的URL進行編碼處理以防止發(fā)生轉(zhuǎn)義婶溯。
處理方式很簡單:
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);
打印結(jié)果為: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
需要解碼回中文的話字節(jié)調(diào)用解碼方法即可类少。