我知道如何以URL格式编码字符串(笑脸是故意的):
let str = "www.mywebsite.com/.html"
let escapedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())!
print(escapedStr)
// Output:
// www.mywebsite.com/%F0%9F%98%80.html
Run Code Online (Sandbox Code Playgroud)
但如果我依附于http://未转义的字符串,Swift也会逃脱冒号:
let str = "http://www.mywebsite.com/.html"
let escapedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())!
print(escapedStr)
// Output
// http%3A//www.mywebsite.com/%F0%9F%98%80.html
Run Code Online (Sandbox Code Playgroud)
如此简单的http://手动删除和添加,我怎样才能正确地删除这些字符串?我必须处理其他前缀https://,ftp://或者ssh://
:不是URL的路径部分中的合法字符.百分比编码所有不在的内容URLPathAllowedCharacterSet,因此编码时不应该感到惊讶:.
URL的每个部分都有不同的编码规则.iOS无法正确编码URL,直到它知道什么部分发生了什么,并且它无法从未编码的字符串中执行此操作(因为它必须首先解析它,并且它无法解析它,因为它不正确已编码).在某些系统(包括旧版本的iOS)中,它会使用各种启发式假设"好吧,我猜你可能意味着......"而不是实际遵循URL编码规则.这是方便的常见情况,而错误编码不太常见但合法的情况(特别是涉及非http URL和非拉丁语URL).iOS现在遵循规则,所以事情编码一致,但这意味着你需要实际考虑URL而不是只是在系统中抛出随机的东西,并希望它能够解决.
这样做的最佳方法(如果你必须动态计算这些东西)是NSURLComponents:
let url = NSURLComponents()
url.scheme = "http"
url.host = "www.mywebsite.com"
url.path = "/.html"
url.string // "http://www.mywebsite.com/%F0%9F%98%80.html"
url.percentEncodedPath // "/%F0%9F%98%80.html"
url.URL // http://www.mywebsite.com/%F0%9F%98%80.html
// etc.
Run Code Online (Sandbox Code Playgroud)
另请参阅NSURLComponents.URLReativeToURL您是否有一些基本静态URL,您不必担心动态编码.
let baseURL = NSURL(string: "http://www.mywebsite.com")
let relative = NSURLComponents()
relative.path = "/.html"
let url = relative.URLRelativeToURL(baseURL)
url?.absoluteString
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1185 次 |
| 最近记录: |