iOS 涉及網絡編程的時候就需要與服務器存在httpurl 交互
如果說url中存在漢字,或者需要上傳圖片,那麼就得考慮urlEncode(否則會出現網址不對)
同樣接收到服務器返回的一些信息可能也存在同樣問題,這時服務器可能會返回urlEcode,客戶端就需要解碼urlDecode
其實方法很簡單,只需創建如下兩個方法即可
編碼 URLEncodedString
-(NSString *)URLEncodedString:(NSString *)str { NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, (CFStringRef)@!*'();:@&=+$,/?%#[], kCFStringEncodingUTF8)); return encodedString; }
解碼 URLDecodedString
-(NSString *)URLDecodedString:(NSString *)str { NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); return decodedString; }
調用方法:
NSString *readyEcodeStr=@adsfa asdfa s+asdf;//准備urlecode的字符串 NSString *ecodeStr=[self URLEncodedString:readyEcodeStr]; NSLog(@readyEcodeStr=%@ ecodeStr=%@,readyEcodeStr,ecodeStr);
打印出來的log如下:
readyEcodeStr=adsfa asdfa s+asdf
ecodeStr=adsfa%20asdfa%20s%2Basdf
ok基本上實現了