【问题标题】:How to encode special character like ’ (NSWindowsCP1250StringEncoding) in Swift2如何在 Swift 2 中编码特殊字符,如'(NSWindow CP1250 字符串编码)
【发布时间】:2015-09-17 13:12:23
【问题描述】:

Swift2 中,stringByAddingPercentEscapesUsingEncoding() 已被弃用,而不是使用 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

【问题讨论】:

  • 试试URLQueryAllowedCharacterSet(),因为特殊字符出现在URL的query部分
  • @vadian 它不起作用。在服务器中,我得到了类似 myName 的 iPhone 的响应
  • URLQueryAllowedCharacterSet() 不起作用
  • 方法stringByAddingPercentEncodingWithAllowedCharacters 需要UTF-8 编码字符串。您可能需要先将字符串从 WindowsCP1250 转换为 UTF-8
  • @vadian 无法解决问题,请帮助我

标签: encoding swift2 ios9 nsurl


【解决方案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"

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

更新:您在 cmets 中声明它仍然无法正常工作,因为您的编码 URL 被截断并包含 ...,但实际上这可能只是一个打印描述 em> 被 NSURL 截断; NSURL 对象包含的实际 URL 应该没问题。否则它将为零。您应该在服务器端检查是否存在 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
  • 为什么当我将上面的 url 传递给我的服务器时,它会返回我的自定义错误
  • 你确定还有错误吗?截断的 url 描述中的点很可能就是打印时截断的 description。 NSURL 持有的实际 url 如果不是 nil,通常是可以的。您应该在服务器端检查带有长(正确)URL 的错误。
【解决方案2】:
let newURLEncodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

【讨论】:

  • 我检查它不适用于特殊字符。在服务器端,它将像 myName 的 iPhone 一样解码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 2016-10-19
  • 1970-01-01
相关资源
最近更新 更多