如何在Swift2中编码像'(NSWindowsCP1250StringEncoding)这样的特殊字符

时间:2015-09-17 13:12:23

标签: encoding swift2 ios9 nsurl

Swift2stringByAddingPercentEscapesUsingEncoding()被弃用,而不是使用stringByAddingPercentEncodingWithAllowedCharacters()

但是如何对特殊字符进行编码,例如'%&在swift2

例如在iOS8(swift1.2)中,我使用以下代码进行编码

NSURL(string: "myurl.php?deviceName=name’phone".stringByAddingPercentEscapesUsingEncoding(NSWindowsCP1250StringEncoding)!)

它工作正常,即在服务器上正确解码。

但在iOS9(Swift2.0)中,我使用了以下代码

NSURL(string: "myurl.php?deviceName=name ’phone".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())!)

无法正确解码。
请告诉我如何在swift2.0中对特殊字符进行编码?

编辑: Eric D的答案是正确的,但当我在stringURL以下进行编码时,它将无法正确编码。 为什么呢?

let stringURL = "https://my.server.com/login.php?e=email&dn=my’s iPad&d=5&er=D550772E-34BB-4DCB-89C9-E746FAD83D24&tz=330"
        print(stringURL)
        let charSet = NSCharacterSet.URLPathAllowedCharacterSet()
        let encoded = stringURL.stringByAddingPercentEncodingWithAllowedCharacters(charSet)!

        let url = NSURL(string: encoded.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())!)!

        print(url) //https%253A//my.server.com/login.php%253Fe=email&dn=my%25E2%2580%2599s%2520iPad&d=5&er=D550772E-34BB-4DCB-89C9-E746FAD83D ... 4&tz=330

编辑2:

如何在 swift2.0 中编码 NSWindowsCP1250StringEncoding

2 个答案:

答案 0 :(得分:1)

使用URLPathAllowedCharacterSet()作为字符集:

let stringURL = "myurl.php?deviceName=name'phone"
let charSet = NSCharacterSet.URLPathAllowedCharacterSet()
let encoded = stringURL.stringByAddingPercentEncodingWithAllowedCharacters(charSet)!
let url = NSURL(string: encoded)!

print(url)  // "myurl.php%3FdeviceName=name'phone"

请注意'不必编码,它是有效的网址字符。

更新:在评论中说明它仍然无效,因为您的编码网址被截断并包含...,但实际上这可能只是一个<由NSURL截断的em>打印描述; NSURL对象包含的实际URL应该没问题。否则它将是零。您应该检查服务器端是否存在长而正确的URL问题。

答案 1 :(得分:0)

let newURLEncodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())