4

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.

3
  • you can create String of url first and then use let URL = URL(string: "") to create final URL. Commented Aug 3, 2017 at 6:01
  • please post the answer Commented Aug 3, 2017 at 6:03
  • even though the accepted answer will technically work, I strongly recommend you review my answer and continue to work with url components. They are more flexible and less prone to error once you become accustomed to them Commented Aug 3, 2017 at 6:38

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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)!
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.