2015-08-04 14 views
8

Ho un dataTaskWithUrl:Come si aggiungono le intestazioni 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() 

voglio aggiungere intestazioni al mio compito.

In altre parole, vorrei convertire questo codice 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; 
}]; 

Sono nuovo di dataRequests. Non capisco il codice Objective C ma ho fatto un'ipotesi quando ho guardato quel codice. Ho bisogno di usare le intestazioni perché se provassi semplicemente ad andare a https://restcountries-v1.p.mashape.com/all direttamente, ricevo un errore. Ho ricevuto questo codice Objective C da questo sito Web: https://www.mashape.com/fayder/rest-countries-v1. Qualsiasi aiuto nella giusta direzione sarebbe molto apprezzato.

Grazie

risposta

5

E 'la stessa risposta @ Leo answer ma la sintassi per Swift ha cambiato un po', che è il motivo per cui penso che sia bene "aggiornare la risposta un po". Quindi questo dovrebbe funzionare con 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 
    } 
5

Se si desidera utilizzare 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() 
+0

Grazie mille @Leo! Esso funziona magicamente. –

Problemi correlati