代码之家  ›  专栏  ›  技术社区  ›  Rizwan Shaikh

如何在Swift2中编码特殊字符,如(NSWindowsCP1250StringEncoding)

  •  1
  • Rizwan Shaikh  · 技术社区  · 10 年前

    如中所示 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中编码特殊字符?

    编辑: 埃里克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:

    如何编码 NSWindowsCP1250String编码 在里面 快速2.0 ?

    2 回复  |  直到 10 年前
        1
  •  1
  •   Eric Aya    10 年前

    使用 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字符。

    更新: 在注释中,您声明它仍然不起作用,因为您的编码URL被截断并包含 ... 但实际上这可能只是 印刷说明 被NSURL截断;NSURL对象所包含的实际URL应该是ok的。否则它将是nil。您应该在服务器端检查非常长但正确的URL是否存在问题。

        2
  •  0
  •   raja    10 年前
    let newURLEncodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
    
    推荐文章