swift - 对查询字符串非常困惑

标签 swift swift2 swift3 alamofire nsurl

我正在使用 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
    }

关于swift - 对查询字符串非常困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689152/

相关文章:

ios - 在下一个 View 中编辑标签很长

ios - 将 UICollectionView 与嵌套部分(堆叠标题)一起使用

swift - ReactiveCocoa 4 MVVM HTTP 请求最佳实践

xcode - 当变量具有特定值时触发函数

ios - 从 UITableViewCell 中快速更改标签文本颜色

swift - 为什么将 coreData 实体附加到设置为 nil 关系的数组中?

swift - 如何使用 AsyncTimerSequence 获取初始时钟,然后开始在指定的时间间隔内迭代?

swift - 'str1.characters'的含义

ios - 在 swift 2 中解析 json 对象

swift - 如何在 URL 中使用特殊字符\n