如何在Swift中调整Mashape应用程序密钥



我尝试使用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)
}

您需要将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,因为它没有任何用处。

相关内容

  • 没有找到相关文章

最新更新