0

I have an app made in Swift/SwiftUI with Xcode 14.2(if that matters).

I have a search field which when changed runs a search() function which parses text and makes an HTTP query. There is some sort of a problem with the way I'm parsing the query (i think) and the app crashes when cyrillic text and emojis are entered (a.k.a. anything that's not plain english).

This is the code I currently have in the app:

func search(query: String) async throws {
    let requestURL = "https://myapilink/api/find?q=\(query)&apikey=areallylongapikey"

    let newRequestURL = requestURL.replacingOccurrences(of: " ", with: "%20")
    var request = URLRequest(url: URL(string: newRequestURL)!)
    let (data, _) = try await URLSession.shared.data(for: request)
    let searchResponse = try JSONDecoder().decode(SearchResponse.self, from: data)
    lists = searchResponse.lists
}

Any help would be appreciated.

Firstly, I was experiencing issues when even entering spaces. I quickly realised that was because the URL expects spaces to be parsed with "%20" - the space symbol equivalent for URLs. I fixed the issue, but later on found another one.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
  • You need to encode all special characters, not just spaces. See https://stackoverflow.com/questions/24551816/swift-encode-url – HangarRash Mar 02 '23 at 17:05
  • "RL(string: newRequestURL)!" is the cause. Not all "characters can be put in a `(NS)URL`, they have to be percent escaped. I'd recommend to use `URLQueryItem` that should escape them for you, adding percent escape on all invalid char, not only spaces. – Larme Mar 02 '23 at 17:21
  • Thanks for the suggestions! @HangarRash's suggestion helped me a bit. I actually ended up just encoding the query and not the URL, as there was no need and actually encoding the URL breaks the app because it replaces the https**://** in the url with %2F etc.. – Tanislav Ivanov Mar 02 '23 at 19:51

0 Answers0