使用URL(string:)构造函数从String获取url

问题描述 投票:0回答:2

我正在创建一个发出API请求的函数。该函数接收一个参数并将其放入API调用中。就像这样:

static func queryCities(cityNameString : String, completion: @escaping (City)->()){
    let urlString = "http://api.geonames.org/searchJSON?q=\(cityNameString)&username=myusername"
    guard let url = URL(string: urlString) else {return}
    print(url)

}

但是仅当我尝试将String转换为URL时,该函数不会返回任何内容。如果我将其粘贴到safari中,则需要精确说明该API调用工作良好。我该如何解决这个问题?

ios swift url
2个回答
2
投票

我建议使用URLComponents来组装您的URL:

static func queryCities(cityNameString : String, completion: @escaping (City)->()) {
    var components = URLComponents(string: "http://api.geonames.org/searchJSON")
    components?.queryItems = [
        URLQueryItem(name: "q", value: cityNameString),
        URLQueryItem(name: "username", value: "myusername")
    ]

    guard let url = components?.url else { return }
    print(url)

    // do the http request here
}


1
投票

检查空间并从String中删除它

 let cityName = "  My CityName  "
 let trimmed = cityName.trimmingCharacters(in: .whitespacesAndNewlines)
© www.soinside.com 2019 - 2024. All rights reserved.