What's the best way to incorporate the possibility of a space being entered in a name in the text field, and then formatting that string w/a space into a URL?
I cannot say what would be the best, but can say using URLComponents would be a very preferable way:
struct APIManager {
//let dataURL = "https://api.openweathermap.org/data/2.5/weather?appid=MyAPIID&units=imperial"
let weatherURL = "https://api.openweathermap.org/data/2.5/weather"
let MyAPIID = "MyAPIID"
var delegate: APIManagerDelegate?
func fetchData(location: String) {
var urlComponents = URLComponents(string: weatherURL)!
urlComponents.queryItems = [
URLQueryItem(name: "appid", value: MyAPIID),
URLQueryItem(name: "units", value: "imperial"),
URLQueryItem(name: "q", value: location),
]
performRequest(url: urlComponents.url)
/*print(urlComponents.url)*/
}
func performRequest(url: URL?) {
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
self.parseJSON(cityData: safeData)
}
}
task.resume()
}
}
//...
}
Topic:
Programming Languages
SubTopic:
Swift
Tags: