【问题标题】:How to print JSON data by Mashape on Swift?如何在 Swift 上通过 Mashape 打印 JSON 数据?
【发布时间】:2014-10-30 01:10:49
【问题描述】:

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

【问题讨论】:

    标签: json api swift mashape


    【解决方案1】:

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

    【讨论】:

    • 我明白了,谢谢。我试过了,发现它对处理 JSON 非常有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多