【问题标题】:URL error char set? [duplicate]URL错误字符集? [复制]
【发布时间】:2018-02-14 18:02:50
【问题描述】:

我尝试使用以下代码调用自定义 url:

let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl)
print(converted)

但我在converted 中得到的结果只是"nil"


我很确定这是因为与 URL() 类相关的错误的字符集

经过一番研究,到目前为止我得到的只是这个过时的 Swift 代码:

var myurl = "https://myserver.com/call?a|b|c"
var newurl = myurl.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
print(newurl)

但它似乎不是这样工作的。

如何使用 (in my case) Swift 4 来避免“nil”结果?

【问题讨论】:

    标签: ios swift url web-applications


    【解决方案1】:

    我自己找到了解决方案:

    let myurl = "https://myserver.com/call?a|b|c"
    let converted = URL(string: myurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    
    print(converted!)
    


    新函数名为addingPercentEncoding,我必须使用urlQueryAllowed 属性调用它。

    urlQueryAllowed 字符集将一些这样的字符添加到 url 编码中:“!*'();:@&=+$,/?%#[]|

    Volià!

    【讨论】:

      猜你喜欢
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2014-03-18
      • 2013-04-14
      • 2022-10-13
      相关资源
      最近更新 更多