2016-05-21 66 views
0

我想通過下面的代碼來訪問字典API:如何在Swift中從NSMutableURLRequest獲取數據?

func apiConnection() { 
     if let url = NSURL(string:"https://wordsapiv1.p.mashape.com/words/soliloquy") { 
     let request = NSMutableURLRequest(URL: url) 
     request.HTTPMethod = "GET" 
     request.addValue("aaabbbccc", forHTTPHeaderField: "X-Mashape-Key") 
     request.addValue("application/json", forHTTPHeaderField: "Accept") 
     print(request.HTTPBody) 

     let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { 
      data, response, error in 
      if error != nil { 
       print("\(error)") 
       return 
      } 

      print("\(response)") 
      let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) 
      print("\(responseString)") 
     } 
    } 
} 

難道我做錯了什麼的代碼?對不起,我在這方面很新。我使用的API是https://market.mashape.com/wordsapi/wordsapi

+0

它看起來像你甚至從來沒有設置HTTPBody。 –

回答

1

您配置的任務,但沒有啓動它

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { 
    ... 
} 
task.resume() // Start the task 
+0

thx很多,它現在有效 –

相關問題