如何在Swift上打印Mashape的JSON数据



我尝试在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")
}

我会试试Alamofire。我知道这也适用于SwiftyJSON。GitHub页面上有一个关于如何使用Alamofire请求/接收响应的好例子。

相关内容

  • 没有找到相关文章

最新更新