我想通过 Swift 实现 `curl --header $1`。(NSURLSession 的标头)
Posted
技术标签:
【中文标题】我想通过 Swift 实现 `curl --header $1`。(NSURLSession 的标头)【英文标题】:I'd like to actualize `curl --header $1` by Swift.( Header of NSURLSession) 【发布时间】:2015-01-06 21:19:07 【问题描述】:我想将以下 curl 操作为 swift。我不知道如何在 Swift 中编写 NSURLSession 的标头。
curl -X GET --header "X-Auth-Token: abcdef" https://devapi.thecurrencycloud.com/v2/rates/detailed?buy_currency=EUR&sell_currency=USD&fixed_side=buy&amount=1000
这是我的代码,但它在句末返回错误。你能告诉我是什么问题吗?
func exchangerate()
let token = "abcdef"
let request = NSMutableURLRequest(URL: NSURL(string: "https://devapi.thecurrencycloud.com/v2/rates/detailed")!)
var buyCurrency = "EUR"
var sellCurrency = "USD"
var fixSide = "buy"
var amount = "1000"
var postString:NSString = "buy_currency=\(buyCurrency)&sell_currency=\(sellCurrency)&fixed_side=\(fixSide)&amount=\(amount)"
request.HTTPMethod = "GET"
request.setValue(token, forHTTPHeaderField: "X-Auth-Token")
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
data, response, error in
if error != nil
println("error=\(error)")
return
println("response = \(response)")
let responseStringExchangeRate = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseStringExchangeRate = \(responseStringExchangeRate)")
task.resume()
error=Error Domain=NSURLErrorDomain Code=-1005 "操作无法完成。(NSURLErrorDomain error -1005.)" UserInfo=0x7fea7b4d63f0 NSErrorFailingURLStringKey=https://devapi.thecurrencycloud.com/v2/rates/detailed, NSErrorFailingURLKey=https://devapi.thecurrencycloud.com/v2/rates/detailed, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x7fea7d805ba0 "操作无法完成。(kCFErrorDomainCFNetwork 错误-1005。)"
【问题讨论】:
【参考方案1】:我已经解决了以下问题。感谢您的帮助。
func exchangerate()
let token = "abcdef"
var buyCurrency = "EUR"
var sellCurrency = "USD"
var fixSide = "buy"
var amount = "1000"
// let request = NSMutableURLRequest(URL: NSURL(string: "https://devapi.thecurrencycloud.com/v2/rates/detailed")!)
var buyCurrency = "EUR"
//var postString:NSString = "buy_currency=\(buyCurrency)&sell_currency=\(sellCurrency)&fixed_side=\(fixSide)&amount=\(amount)"
let request = NSMutableURLRequest(URL: NSURL(string: "https://devapi.thecurrencycloud.com/v2/rates/detailed?buy_currency=\(buyCurrency)&sell_currency=\(sellCurrency)&fixed_side=\(fixSide)&amount=\(amount)")!)
request.HTTPMethod = "GET"
request.setValue(token, forHTTPHeaderField: "X-Auth-Token")
// request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
data, response, error in
if error != nil
println("error=\(error)")
return
println("response = \(response)")
let responseStringExchangeRate = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseStringExchangeRate = \(responseStringExchangeRate)")
task.resume()
【讨论】:
以上是关于我想通过 Swift 实现 `curl --header $1`。(NSURLSession 的标头)的主要内容,如果未能解决你的问题,请参考以下文章