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

时间:2014-12-31 16:49:20

标签: ios swift text-analysis mashape

我正在尝试学习如何将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.

}

如何返回&#34;结果&#34;在json中作为字符串?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

在这段代码中,我发出了一个HTTP请求,并从我的示例php文件中获取JSON数据:

        // Making the HTTP request

        var post:NSString = "data=\(data)"

        NSLog("PostData: %@",post)

        var url:NSURL = NSURL(string: "http://domain.com/jsontest.php")!

        var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

        var postLength:NSString = String( postData.length )

        var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")


        var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

        if ( urlData != nil ) {
            let res = response as NSHTTPURLResponse!

            NSLog("Response code: %ld", res.statusCode)

            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                NSLog("Response ==> %@", responseData)

                var error: NSError?


                // Here i make the JSON dictionary

                let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

                // Like this you can access the values of the JSON dictionary as string

                name.text = jsonData.valueForKey("name") as NSString
                last.text = jsonData.valueForKey("last") as NSString

            }
        }

希望有所帮助:)