iOS 字符串含有特殊字符,轉換URL爲空值

 
網略請求的url含有特殊字符時字符串須要編碼處理
好比:url:http://demo.demo.com/demo?{userToken:xxxxxx}等等,都須要字符串處理,不然轉換成NSURL可能爲空值。
 

第一種方法

url含有中文的解決方法html

 NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlStr,NULL,NULL,kCFStringEncodingUTF8));編碼

urlStr是url地址,拼接中含有中文。url

 

第二種方法

// 在對URL中的中文進行轉碼時,iOS 9以前咱們使用
 [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//編碼
// iOS 9以後使用  
 [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//編碼
 
URLQueryAllowedCharacterSet組件是可選的
編碼字符範圍
URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

解碼:[@"編碼後的字符串" stringByRemovingPercentEncoding];//解碼spa


NSURL 轉換字符串能夠直接使用NSURL的屬性absoluteString
例如上述的url,NSString * urlStr = url.absoluteString;.net

 

使用上面的方法無效,解決方法使用這個code

//urlEncode編碼htm

NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";blog

NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];字符串

NSString * stringUrl = [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];get

//urlEncode解碼

NSMutableString *outputStr = [NSMutableString stringWithString:input];

[outputStr replaceOccurrencesOfString:@"+" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[outputStr length])];

[outputStr stringByRemovingPercentEncoding];

 

    

 

 

參考:https://www.jianshu.com/p/b7dde2b1e992

   http://blog.csdn.net/olive1993/article/details/52036755

   https://www.tpyyes.com/a/kuozhan/2017/0406/89.html

相關文章
相關標籤/搜索