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
You need to encode those characters as well. You can check what percent escaped values are for
{and}and put them in manually. But I rather suggest you have the ability to create a query string from dictionary. Something like the following should fix your issue:Now all you need to do is use it and ensure
jsonArgs={\"AccountID\":%d}is used in a dictionary as well. Try something like: