URL轉譯 stringByAddingPercentEscapesUsingEncoding(只對 `#%^{}[]|"<> 加空格共14個字元編碼,不包括”&?”等符號), ios9將淘汰。 建議用stringByAddingPercentEncodingWithAllowedCharacters方法
//中文連結
NSString *globalURL = [[NSString alloc]initWithFormat:@"http://127.0.0.1:%d/oa/workflow/submit/workflow?requestId=181193&userNumber=01281209&type=submit&remark=這是個什麼鬼啊,這是個神",ListenPort];
//iOS9.0廢棄方法
//NSString * encodingString = [globalURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//轉譯後的連結
NSString * encodingString = [globalURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
複製程式碼
stringByAddingPercentEncodingWithAllowedCharacters需要傳一個
NSCharacterSet物件(關於 NSCharacterSet 這篇 文章說的很好)
如[NSCharacterSet URLQueryAllowedCharacterSet]
@interface NSCharacterSet (NSURLUtilities)
// 預定義字符集用於六個URL元件和子元件,它們允許百分比編碼。
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters
// 包含URL使用者子元件中允許的字元的字符集
@property (class, readonly, copy) NSCharacterSet *URLUserAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
// 包含URL密碼子元件中允許的字元的字符集
@property (class, readonly, copy) NSCharacterSet *URLPasswordAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
// 包含URL的主機子元件中允許的字元的字符集
@property (class, readonly, copy) NSCharacterSet *URLHostAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
// 返回一個包含字元的字符集允許URL的路徑元件。字元“;”是一種合法的路徑,但是建議最好是percent-encoded相容NSURL(-stringByAddingPercentEncodingWithAllowedCharacters:percent-encode任何‘;’字元如果你通過URLPathAllowedCharacterSet)
@property (class, readonly, copy) NSCharacterSet *URLPathAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
// 包含URL查詢元件中允許的字元的字符集
@property (class, readonly, copy) NSCharacterSet *URLQueryAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
// 包含URL片段元件中允許的字元的字符集
@property (class, readonly, copy) NSCharacterSet *URLFragmentAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
@end
編碼字元範圍
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
複製程式碼
END