【作者前言】:13年入圈,分享些本人工作中遇到的點(diǎn)點(diǎn)滴滴那些事兒蛛芥,17年剛開(kāi)始寫(xiě)博客提鸟,高手勿噴!以分享交流為主仅淑,歡迎各路豪杰點(diǎn)評(píng)改進(jìn)称勋!
1.應(yīng)用場(chǎng)景:
鏈接分享場(chǎng)景非常之多,為了更好的保護(hù)一些數(shù)據(jù)信息涯竟,需要我們進(jìn)行一些編解碼處理
這里為了能夠跟Web互通赡鲜,整理了一下。
2.實(shí)現(xiàn)目標(biāo):
跨平臺(tái)url數(shù)據(jù)編解碼互通庐船, 保護(hù)數(shù)據(jù)信息安全性
3.代碼說(shuō)明:
① url encodeURIComponent 編碼
//MARK: - encodeURIComponent:
/**
* @brief url編碼處理
* @param urlStr - 待編碼的鏈接字符串
* @return 編碼完成后的鏈接字符串
*/
+ (NSString *)yp_encodeURIComponent:(NSString *)urlStr{
NSString *encodedUrl = nil;
if (@available(iOS 9.0, *)) {
NSMutableCharacterSet *set = [NSMutableCharacterSet new];
[set formUnionWithCharacterSet:([NSMutableCharacterSet alphanumericCharacterSet])];
[set formUnionWithCharacterSet:([NSMutableCharacterSet characterSetWithCharactersInString:@"-_.!~*'()"])];
encodedUrl = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
}else {
encodedUrl = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlStr, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
}
return encodedUrl;
}
② URL decodeURIComponent 解碼
//MARK: - decodeURIComponent:
/**
* @brief url 解碼處理
* @param urlStr - 待解碼的鏈接字符串
* @return 解碼完成后的鏈接字符串
*/
+ (NSString *)yp_decodeURIComponent:(NSString *)urlStr {
NSString *decodedUrl = nil;
if (@available(iOS 9.0, *)) {// 當(dāng)前版本 >= 9.0 可用
decodedUrl = [urlStr stringByRemovingPercentEncoding];
}else {
decodedUrl = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (__bridge CFStringRef)urlStr, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
}
return decodedUrl;
}