Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add headers to dataTaskWithUrl?

Tags:

json

ios

swift

I have a 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()

I want to add headers to my task.

In other words, I would like to convert this code to 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;
}];

I am new to dataRequests. I do not understand Objective C code but I made a guess when I looked at that code. I need to use headers because I if I just try going to https://restcountries-v1.p.mashape.com/all directly, I get an error. I had received that Objective C code from this website: https://www.mashape.com/fayder/rest-countries-v1. Any help in the right direction would be very much appreciated.

Thanks

like image 985
Ujjwal-Nadhani Avatar asked Aug 04 '15 01:08

Ujjwal-Nadhani


2 Answers

Update for 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()

Old Post:

If you want to use 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()
like image 80
Leo Avatar answered Nov 18 '22 21:11

Leo


It's the same answer as @Leo's answer but the syntax for Swift changed a little which is why I think it's good to "update the answer a little". So this should work with 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
  }
like image 15
Jason Saruulo Avatar answered Nov 18 '22 22:11

Jason Saruulo