Please consider below code that I implemented in my iOS App:
let kBaseURL = "https://www.sampledomain.com/"
let method = "api/MasterData/GetCompanyList?jsonArgs={\"AccountID\":%d}"
private func prepareURL(api: String) -> String {
return (kBaseURL + api).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}
In above code, "method" has "%d" which will be replaced by account id (at run time) that is an integer.
let accountID = 20
let methodToCall = String(format: method, accountID)
var apiRequest = URLRequest(url: URL(string: prepareURL(api: methodToCall))!)
Above code is crashing as URL is nil which is due to "method" that has special characters in it.
Crash reason given by Xcode is: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
As found in Apple's doc, if you have some characters in the string which are illegal in a URL, URL(string:) returns nil. At this case, you need to % encode as follows.
So you need to mofify to
I came across the same issue when I was handling non-English letters; for my case they are "Kanji". So, I always use percent encoding w/o checking what's in the string when calling URL(string:). Actually, there are so many illegal URL letters w/ "Kanji" and it's next to impossible to check what's legal and what's not manually. URL(string:) w/ the percent encoded string by addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) always works nicely for me.