ios - 在 ios9 中替换 stringByAddingPercentEscapesUsing

在 iOS8 及之前我可以使用:

NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

在 iOS9 中 stringByAddingPercentEscapesUsingEncoding 已被替换为 stringByAddingPercentEncodingWithAllowedCharacters:

NSString *str = ...; // some URL
NSCharacterSet *set = ???; // where to find set for NSUTF8StringEncoding?
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];

我的问题是:在哪里可以找到所需的 NSCharacterSet (NSUTF8StringEncoding) 以正确替换 stringByAddingPercentEscapesUsingEncoding

最佳答案

弃用消息说(强调我的):

Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.

所以你只需要提供一个足够的 NSCharacterSet 作为参数。幸运的是,对于 URL,有一个非常方便的类方法,称为 URLHostAllowedCharacterSet,您可以像这样使用它:

let encodedHost = unencodedHost.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

Swift 3 的更新——该方法变为静态属性 urlHostAllowed:

let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

但请注意:

This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string.

关于ios - 在 ios9 中替换 stringByAddingPercentEscapesUsingEncoding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32242712/

相关文章:

ios - 如何以编程方式检查 iOS 应用程序中是否存在键盘?

ios - 检测到约束模糊地表明高度为零的情况

ios - 从 iPhone 上的 NSString 中删除 HTML 标签

ios - 添加一个简单的 UIAlertView

c - 先学C再学Objective-C

ios - 如果没有 Table View 结果,在屏幕上显示 "No Results"

objective-c - 在 Objective-C 中向 nil 发送消息

objective-c - Objective-C 中 `oneway void` 的用例?

objective-c - 从当前日期减去 7 天

objective-c - 如何将 NSTimeInterval(秒)转换为分钟