我尝试使用Mashape的"Yoda to“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)
}发布于 2014-10-17 22:59:40
您需要将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,因为它没有任何用处。
https://stackoverflow.com/questions/26401404
复制相似问题