1

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
                }
            }
User123
  • 37
  • 1
  • 6
  • 1
    In general, you should never use `!` to force unwrap, as there's a risk of crash. In terms of getting a valid url, does this answer your question? https://stackoverflow.com/a/48946469/560942 – jnpdx Apr 08 '21 at 19:56

1 Answers1

1

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
}
Pyry Lahtinen
  • 459
  • 1
  • 3
  • 6