If I understand you correctly, you want to encode spaces as +
and encode other special characters correctly as well.
So this approach uses the native function addingPercentEncoding(withAllowedCharacters:)
that translates a sspaces to %20
. Afterwards we replace all occurrences of %20
with a +
.
extension URL {
init?(encoding string: String) {
let encodedString = string
.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
.replacingOccurrences(of: "%20", with: "+")
guard let encodedString != nil else { return nil }
self.init(string: encodedString!)
}
}
This is encapsulated in an URL
init function, so you can use it like this:
let requestUrl = URL(encoding: "http://api.openweathermap.org/data/2.5/weather?appid=dca0aa44807a0bc05ed51c6a85472341&q="+"New York")