将String转换为URL返回nil

时间:2017-02-10 05:14:31

标签: swift3

var url:String = "http://112.199.178.73:4000/contact" + "?" + ["accessToken": getAppDelegate().applicationData?.accessToken].queryStringWithEncoding();

var socketUrl = URL(string: url);

1 个答案:

答案 0 :(得分:2)

不要像这样手动构建网址和网址字符串。

var components = URLComponents()
components.scheme = "http"
components.host = "112.199.178.73"
components.port = 4000
components.path = "/contact"

// I'm assuming accessToken is a string here
if let accessToken = getAppDelegate().applicationData?.accessToken {
    components.queryItems = [
        URLQueryItem(name: "accessToken", value: accessToken)
    ]
}

guard let url = components.url else {
    fatalError("Failed to create URL")
}

如果您可以发布var url:String = "http://112.199.178.73:4000/contact" + "?" + ["accessToken": getAppDelegate().applicationData?.accessToken].queryStringWithEncoding(); 生成的字符串,我们可以确切地告诉您出错了什么,但我敢打赌,但["accessToken": getAppDelegate().applicationData?.accessToken].queryStringWithEncoding();附加到该字符串会给您带来一个不正确的网址字符串。