如何在 iOS 中进行 URL 解码 - Objective C
stringByReplacingPercentEscapesUsingEncoding 方法无法正常工作,因为它无法解码不以 % 字符(即 + 字符)开头的特殊符号。有谁知道在 iOS 中执行此操作的更好方法吗?
这是我当前正在使用的:
NSString *path = [@"path+with+spaces"
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
这是输出的示例:
path+with+spaces
The stringByReplacingPercentEscapesUsingEncoding method is not working properly as it's not decoding special symbols that dont start with a % character, i.e., the + character. Does anyone know of a better method to do this in iOS?
Here's what I'm currently using:
NSString *path = [@"path+with+spaces"
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
And here's an example of the output:
path+with+spaces
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请注意,加号替换空格仅用于
application/x-www-form-urlencoded
数据 - URL 的查询字符串部分或POST
的正文代码> 请求。Note that the plus-for-space substitution is only used in
application/x-www-form-urlencoded
data - the query string part of a URL, or the body of aPOST
request.http://cybersam.com/ios-dev/proper-url -percent-encoding-in-ios
这似乎是首选方式,因为......
“显然”这是苹果意识到的一个“错误”,但他们还没有采取任何措施......( http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/ )
http://cybersam.com/ios-dev/proper-url-percent-encoding-in-ios
This seems to be the preferred way because...
"Apparently" this is a "bug" apple is aware of, but they haven't done anything about it yet... ( http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/ )
如果您尝试将加号替换为百分号转义符,请执行从“+”到“ ”(单个空格)的字符串替换。然后使用 stringByAddingPercentEscapesUsingEncoding: 来添加百分比转义。
加号是许多从未编码的保留 URL 字符之一。
(
stringByReplacingPercentEscapesUsingEncoding:
解码百分比转义)If you are trying to replace the plus sign with percent escapes, perform a string replacement from "+" to " " (single space). Then use
stringByAddingPercentEscapesUsingEncoding:
to add the percent escapes.The plus sign is one of many reserved URL characters that is never encoded.
(
stringByReplacingPercentEscapesUsingEncoding:
decodes the percent escapes)迅速2:
swift 2 :
您还可以使用 Cocoapods 中的 PercentEncoder 库。
Swift 4
将库包含到您的 Podfile 中:
pod PercentEncoder
导入库 PercentEncoder
导入 PercentEncoder
视图控制器类{
...
}
将“+”字符替换为“%20”并使用方法“ped_decodeURI”< /p>
"path+with+spaces".replacingOccurrences(of: "+", with: "%20").ped_decodeURI()
它将返回“带空格的路径”
这里是参考链接:https://cocoapods.org/pods/PercentEncoder
Also you can use the PercentEncoder library from Cocoapods.
Swift 4
Include the library to your Podfile:
pod PercentEncoder
Import the library PercentEncoder
import PercentEncoder
class ViewController{
...
}
Replace the "+" character by "%20" and use the method "ped_decodeURI"
"path+with+spaces".replacingOccurrences(of: "+", with: "%20").ped_decodeURI()
It will return "path with spaces"
Here the link for reference: https://cocoapods.org/pods/PercentEncoder