I have an API URL where I input a street name through the variable self.origin.input
. This works all well and fine untill I input a street name with a non english character for example Å , Ä and Ö which are common characters here in Sweden. If I do this I get the error message:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Does anyone know how to fix this?
Here is the part of my code where the error occurs:
let locationUrl = URL(string: "https://nominatim.openstreetmap.org/search?country=Sweden&city=Stockholm&street=\(self.origin.input)&format=json")
URLSession.shared.dataTask(with: locationUrl!) {data, response, error in
if let data = data {
// My logic here
}
}
I think that you should use URL encoding. In Swift this happens like so:
let urlStr = "https://nominatim.openstreetmap.org/search?country=Sweden&city=Stockholm&street=\(self.origin.input)&format=json"
let urlEncoded = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: urlEncoded)
I also highly recommend that you get rid of force unwrapping with !
. You can use
guard let url = URL(string: urlEncoded) else { /* handle nil here */ }
or
if let url = URL(string: urlEncoded) {
// url is not nil
} else {
// url is nil
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.