Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何使用URL向DataTask添加标题?_Ios_Json_Swift - Fatal编程技术网

Ios 如何使用URL向DataTask添加标题?

Ios 如何使用URL向DataTask添加标题?,ios,json,swift,Ios,Json,Swift,我有一个带有URL的数据任务: var headers: NSDictionary = ["X-Mashape-Key": "my-secret-key" , "Accept" : "application/json"] var stringUrl = "https://restcountries-v1.p.mashape.com/all" stringUrl = stringUrl.stringByReplacingOccurrencesOfSt

我有一个带有URL的
数据任务

        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()
我想向我的任务添加标题

换句话说,我想将此代码转换为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;
}];
我不熟悉数据请求。我不理解客观的C代码,但当我看到那个代码时,我做了一个猜测。我需要使用标题,因为如果我尝试 我直接得到一个错误。我已从该网站收到目标C代码:。如果能在正确的方向上提供帮助,我们将不胜感激


感谢您更新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()
旧帖子

如果要使用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()

这与@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
  }
如何在此请求中添加词典??setValue(myDictionary,forHTTPHeaderField:“headerField”)。我已经试过了,但这是只接受字符串格式。如何在这个请求中添加,字典??setValue(myDictionary,forHTTPHeaderField:“headerField”)。我已经试过了,但这是只接受字符串格式的。