对查询字符串非常困惑

Massively Confused About Query Strings

我正在使用 AlamoFire 发出 API 请求。连接到 API 非常简单,具有巨大挑战性的是查询 API。

我正在尝试创建一个与此类似的查询字符串:

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

我觉得我已经在互联网上搜索了很多关于这个主题的文档,但都没有找到..

是否有人可以分享有关查询字符串的任何资源或建议?

创建查询字符串的最简单方法是使用 URLComponents,它会为您处理所有百分比转义:

// 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")
}

那是纯粹的Swift,你应该熟悉一下。一旦您掌握了基础知识,Alamofire 可以为您简化它:

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
    }