我正在创建一个发出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调用工作良好。我该如何解决这个问题?
我建议使用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
}
检查空间并从String
中删除它
let cityName = " My CityName "
let trimmed = cityName.trimmingCharacters(in: .whitespacesAndNewlines)