Search code examples
iosswifttext-analysismashape

How can I return the json property of this swiftHTTP function as a string?


I am trying to learn how to use swiftHTTP with a mishap api (https://www.mashape.com/textanalysis/textanalysis). This is my code so far,

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.

}

How can I return the "result" in the json as a string?


Solution

  • SwiftHTTP, like NSURLSession, is async by design. Meaning that you can not just return from the method.

    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)")
        })
    }
    

    Then you would use it like this.

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

    Also see this Github issue as well.

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