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

时间:2014-10-16 09:57:01

标签: ios api swift mashape

我尝试使用" Yoda Speak" Mashape的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)
}

1 个答案:

答案 0 :(得分: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,因为它没用。