gpt4 book ai didi

ios - 如何将此 swiftHTTP 函数的 json 属性作为字符串返回?

转载 作者:行者123 更新时间:2023-11-28 13:18:32 25 4
gpt4 key购买 nike

我正在尝试学习如何将 swiftHTTP 与 mishap api ( https://www.mashape.com/textanalysis/textanalysis ) 一起使用。到目前为止,这是我的代码,

import SwiftHTTP

func splitSentenceIntoWordsUsingTextAnalysis (string: String) -> String {
var request = HTTPTask()
var params = ["text": "这是中文测试"] //: Dictionary<String,AnyObject>
//request.requestSerializer = JSONRequestSerializer()
request.requestSerializer.headers["X-Mashape-Key"] = "My-API-Key"
request.requestSerializer.headers["Content-Type"] = "application/x-www-form-urlencoded"
request.responseSerializer = JSONResponseSerializer()
request.POST("https://textanalysis.p.mashape.com/segmenter", parameters: params, success: {(response: HTTPResponse) in if let json: AnyObject = response.responseObject { println("\(json)") } },failure: {(error: NSError, response: HTTPResponse?) in println("\(error)") })

// {
// result = "\U4f60 \U53eb \U4ec0\U4e48 \U540d\U5b57";
// }

return ?? // I want to return the "result" in the json as a string.

}

如何将 json 中的“结果”作为字符串返回?

最佳答案

SwiftHTTP 和 NSURLSession 一样,在设计上是异步的。这意味着您不能只从该方法返回。

import SwiftHTTP

func splitSentenceIntoWordsUsingTextAnalysis (string: String, finished:((String) -> Void)) {
var request = HTTPTask()
var params = ["text": "这是中文测试"] //: Dictionary<String,AnyObject>
//request.requestSerializer = JSONRequestSerializer()
request.requestSerializer.headers["X-Mashape-Key"] = "My-API-Key"
request.requestSerializer.headers["Content-Type"] = "application/x-www-form-urlencoded"
request.responseSerializer = JSONResponseSerializer()
request.POST("https://textanalysis.p.mashape.com/segmenter", parameters: params, success: {
(response: HTTPResponse) in
if let res: AnyObject = response.responseObject {
// decode res as string.
let resString = res as String
finished(resString)
}
}, failure: {(error: NSError, response: HTTPResponse?) in
println(" error \(error)")
})
}

然后你会像这样使用它。

splitSentenceIntoWordsUsingTextAnalysis("textToSplit", {(str:String) in
println(str)
// do stuff with str here.
})

另请参阅此 Github 问题。

https://github.com/daltoniam/SwiftHTTP/issues/30

关于ios - 如何将此 swiftHTTP 函数的 json 属性作为字符串返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27723917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com