Search code examples
swiftswift2swift3alamofirensurl

Massively Confused About Query Strings


I am using AlamoFire to make an API request. Connecting to the API has been pretty straight forward, what has been massively challenging is querying the API.

I am attempting to create a query string similar to this:

https://api-fxtrade.oanda.com/v3/instruments/USD_CAD/candles?price=BA&from=2016-10-17T15%3A00%3A00.000000000Z&granularity=M1

I feel like I have explored a lot of the internet for documentation on the subject and have come up short..

Does anyone have any resources or advice to share about query strings?


Solution

  • The easiest way to make a query string is to use URLComponents, which handles all the percentage escape for you:

    // Keep the init simple, something that you can be sure won't fail
    var components = URLComponents(string: "https://api-fxtrade.oanda.com")!
    
    // Now add the other items to your URL query
    components.path = "/v3/instruments/USD_CAD/candles"
    components.queryItems = [
        URLQueryItem(name: "price", value: "BA"),
        URLQueryItem(name: "from", value: "2016-10-17T15:00:00.000000000Z"),
        URLQueryItem(name: "granularity", value: "M1")
    ]
    
    if let url = components.url {
        print(url)
    } else {
        print("can't make URL")
    }
    

    That is with pure Swift, which you should familiarize yourself with. Once you have master the basics, Alamofire can simplify it for you:

    let params = [
        "price": "BA",
        "from": "2016-10-17T15:00:00.000000000Z",
        "granularity": "M1"
    ]
    Alamofire.request("https://api-fxtrade.oanda.com/v3/instruments/USD_CAD/candles", parameters: params)
        .responseData { response in
            // Handle response
        }