我尝试在 Swift 中使用 Mashape 的“Yoda Speak”API。我将从 API 打印数据。我在“getData”方法之后成功调用了“response”方法,但我的模拟器不在“response”方法中。我知道有一些类似的问题,但我不能。请给我一些建议。
func response(res: NSURLResponse!, data: NSData!, error: NSError!) {
println("response")
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
} else {
println("succeeded")
}
// simulator is out here.
var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
for value in json {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
println(value)
})
}
}
func getData() {
println("getData")
// URL.
let url = NSURL(string: "https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait.")!
// URLRequest.
var req = NSMutableURLRequest(URL: url)
// header.
req.setValue("jY0bEhHCBpmsh8j1mpA5p11tCJGyp1tok3Zjsn4ubbvNNp5Jt3", forHTTPHeaderField: "X-Mashape-Key")
let connection: NSURLConnection = NSURLConnection(request: req, delegate: self, startImmediately: false)!
// Connection to the server.
NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue.mainQueue(), completionHandler: self.response)
println("complete")
}