2

我尝试使用 Mashape 的“Yoda Speak”API。我得到了二进制数据,但我不知道如何解析数据。当我尝试打印数据时,我收到了这条消息。“(消息,缺少 Mashape 应用程序密钥。转到https://www.mashape.com获取您的密钥。)”我认为 Mashape 应用程序密钥是“jY0bEhHCBpmsh8j1mpA5p11tCJGyp1tok3Zjsn4ubbvNNp5Jt3”。

如何在 Swift 中调整这个键?

    func response(res: NSURLResponse!, data: NSData!, error: NSError!) {

    let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
    let header: NSDictionary = ["X-Mashape-Key" : "jY0bEhHCBpmsh8j1mpA5p11tCJGyp1tok3Zjsn4ubbvNNp5Jt3"]

    for value in json {
        println(value)
    }
}

func getData() {
   let url = NSURL(string: "https://yoda.p.mashape.com/yoda?sentence=I+like+you")!
    let req = NSURLRequest(URL: url)
    let connection: NSURLConnection = NSURLConnection(request: req, delegate: self, startImmediately: false)!

    NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue.mainQueue(), completionHandler: response)
}
4

1 回答 1

3

您需要将 设置X-Mashape-Key为您的NSURLRequest. 为此:

let req = NSMutableURLRequest(URL: url)
req.setValue("jY0bEhHCBpmsh8j1mpA5p11tCJGyp1tok3Zjsn4ubbvNNp5Jt3", forHTTPHeaderField: "X-Mashape-Key")

NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue.mainQueue(), completionHandler: response)

应该做的伎俩。然后,您可以从响应处理程序中删除标头NSDictionary,因为它没有用。

于 2014-10-17T22:59:40.497 回答