如何向dataTaskWithUrl添加标头?

Ujj*_*ani 14 json ios swift

我有一个dataTaskWithUrl:

        var headers: NSDictionary = ["X-Mashape-Key": "my-secret-key" , "Accept" : "application/json"]
        var stringUrl = "https://restcountries-v1.p.mashape.com/all"
        stringUrl = stringUrl.stringByReplacingOccurrencesOfString(" ", withString: "+")
        let url = NSURL(string: stringUrl)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

        if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary{

           println(jsonResult)

        }else{
            println("error")
        }

      })

       task.resume()
Run Code Online (Sandbox Code Playgroud)

我想在我的任务中添加标题.

换句话说,我想将此代码转换为swift:

NSDictionary *headers = @{@"X-Mashape-Key": @"my-secret-key", @"Accept": @"application/json"};
UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
  [request setUrl:@"https://restcountries-v1.p.mashape.com/all"];
  [request setHeaders:headers];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
  NSInteger code = response.code;
  NSDictionary *responseHeaders = response.headers;
  UNIJsonNode *body = response.body;
  NSData *rawBody = response.rawBody;
}];
Run Code Online (Sandbox Code Playgroud)

我是dataRequests的新手.我不了解Objective C代码,但是当我查看该代码时我猜了一下.我需要使用标题,因为如果我直接尝试访问 https://restcountries-v1.p.mashape.com/all,我会收到错误消息.我从这个网站收到了Objective C代码:https://www.mashape.com/fayder/rest-countries-v1.我们非常感谢任何正确方向的帮助.

谢谢

Leo*_*Leo 14

Swift 4+ 更新:

let httpUrl = "http://...."
guard let url = URL(string: httpUrl) else {
    return
}
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("my-secret-key", forHTTPHeaderField: "X-Mashape-Key")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

}
task.resume()
Run Code Online (Sandbox Code Playgroud)

旧帖子:

如果要使用dataTask

    var stringUrl = "https://restcountries-v1.p.mashape.com/all"
    stringUrl = stringUrl.stringByReplacingOccurrencesOfString(" ", withString: "+")
    let url = NSURL(string: stringUrl)
    let session = NSURLSession.sharedSession()
    var muableRequest = NSMutableURLRequest(URL: url!)
    muableRequest.setValue("application/json", forHTTPHeaderField: "Accept")
    muableRequest.setValue("my-secret-key", forHTTPHeaderField: "X-Mashape-Key")

    let task = session.dataTaskWithRequest(muableRequest, completionHandler: { (data, response, error) -> Void in
        if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil){

            println(jsonResult)

        }

    })
    task.resume()
Run Code Online (Sandbox Code Playgroud)


Jas*_*ulo 9

这与@Leo的回答是一样的答案,但Swift的语法稍有改变,这就是为什么我认为"稍微更新答案"的好处.所以这适用于Swift 3.

func get(_ url: String) {
  if let url = URL(string: url) {
    var request = URLRequest(url: url)
    // Set headers
    request.setValue("headerValue", forHTTPHeaderField: "headerField")
    request.setValue("anotherHeaderValue", forHTTPHeaderField: "anotherHeaderField")
    let completionHandler = {(data: Data?, response: URLResponse?, error: Error?) -> Void in
      // Do something
    }
    URLSession.shared.dataTask(with: request, completionHandler: completionHandler).resume()
  } else {
    // Something went wrong
  }
Run Code Online (Sandbox Code Playgroud)