iOS urlstr包含特殊字符转码问题

2021-10-14  本文已影响0人  丿小七

最近总是忘记给转URL的字符串进行编码,导致链接中包含特殊字符的时候总是出错。
记录下转码方式:

NSString *urlStrEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

个人理解就是针对URL的组成部分进行编码,个人常用URLQueryAllowedCharacterSet

返回一个字符集,其中包含URL的用户子组件中允许的字符。

返回一个包含URL密码子组件中允许的字符的字符集。

返回一个包含URL的宿主子组件中允许的字符的字符集。

返回一个包含URL路径组件中允许的字符的字符集。';'是一个合法的路径字符,但为了与NSURL最好的兼容,建议使用百分比编码(-stringByAddingPercentEncodingWithAllowedCharacters:如果你传递URLPathAllowedCharacterSet,将百分比编码任何';'字符)。

返回一个包含URL查询组件中允许的字符的字符集。

返回包含URL片段组件中允许的字符的字符集。


// Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.

// Returns a character set containing the characters allowed in a URL's user subcomponent.
@property (class, readonly, copy) NSCharacterSet *URLUserAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));

// Returns a character set containing the characters allowed in a URL's password subcomponent.
@property (class, readonly, copy) NSCharacterSet *URLPasswordAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));

// Returns a character set containing the characters allowed in a URL's host subcomponent.
@property (class, readonly, copy) NSCharacterSet *URLHostAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));

// Returns a character set containing the characters allowed in a URL's path component. ';' is a legal path character, but it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet).
@property (class, readonly, copy) NSCharacterSet *URLPathAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));

// Returns a character set containing the characters allowed in a URL's query component.
@property (class, readonly, copy) NSCharacterSet *URLQueryAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));

// Returns a character set containing the characters allowed in a URL's fragment component.
@property (class, readonly, copy) NSCharacterSet *URLFragmentAllowedCharacterSet API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
上一篇 下一篇

猜你喜欢

热点阅读