Reputation: 1733
I have an URL with
https://api.asiancar.com/api/applicationsettings
It is basically a GET url so I need to pass a boolean
"isMobile" and timestamp
as query parameters . How to achieve this as the ultimate URL after passing the query will look like this:
https://api.asiancar.com/api/applicationsettings?timestamp=111122244556789879&isMobile=true
let queryItems = [
NSURLQueryItem(timestamp: "1234568878788998989", isMobile: true),
NSURLQueryItem(timestamp: "1234568878788998989", isMobile: true)
]
let urlComps = NSURLComponents(string: "www.api.asiancar.com/api/applicationsettings")!
urlComps.queryItems = queryItems
let URL = urlComps.URL!
Am I doing right or any other modification ? please tell.
Upvotes: 4
Views: 9380
Reputation: 5182
You can try an alternative way by using String
let baseUrlString = "https://api.asiancar.com/api/"
let timeStamp = 1234568878788998989
let isMobile = true
let settingsUrlString = "\(baseUrlString)applicationsettings?timestamp=\(timeStamp)&isMobile=\(isMobile)"
print(settingsUrlString)
let url = URL(string: settingsUrlString)
output : https://api.asiancar.com/api/applicationsettings?timestamp=1234568878788998989&isMobile=true
Upvotes: 1
Reputation: 8322
Try this :
let API_PREFIX = "www.api.asiancar.com/api/applicationsettings"
var url : URL? = URL.init(string: API_PREFIX + queryItems(dictionary: [name: "isMobile", value: "true"] as [String : Any]))
func queryItems(dictionary: [String:Any]) -> String {
var components = URLComponents()
print(components.url!)
components.queryItems = dictionary.map {
URLQueryItem(name: $0, value: $1 as String)
}
return (components.url?.absoluteString)!
}
Upvotes: 1
Reputation: 3235
Unless you have subclassed NSURLQueryItem
, then your init method is not correct. Per Apple's documentation for NSURLQueryItem
, the init method signature is:
init(name: String, value: String?)
This means your query items should be created like this:
let queryItems = [NSURLQueryItem(name: "timestamp" value: "1234568878788998989"), NSURLQueryItem(name: "isMobile", value: "true")]
This will properly add them to the url in the format you are expecting.
Upvotes: 3