Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/121.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何以字符串形式返回此swiftHTTP函数的json属性?_Ios_Swift_Text Analysis_Mashape - Fatal编程技术网

Ios 如何以字符串形式返回此swiftHTTP函数的json属性?

Ios 如何以字符串形式返回此swiftHTTP函数的json属性?,ios,swift,text-analysis,mashape,Ios,Swift,Text Analysis,Mashape,我正在尝试学习如何将swiftHTTP与mishap api()结合使用。这是我到目前为止的代码 import SwiftHTTP func splitSentenceIntoWordsUsingTextAnalysis (string: String) -> String { var request = HTTPTask() var params = ["text": "这是中文测试"] //: Dictionary<String,AnyObject>

我正在尝试学习如何将swiftHTTP与mishap api()结合使用。这是我到目前为止的代码

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.

}
导入快捷http
func splitSentenceIntoWordsUsingTextAnalysis(string:string)->string{
var request=HTTPTask()
变量参数=[“文本”:这是中文测试"] //: 字典
//request.requestSerializer=JSONRequestSerializer()
request.requestSerializer.headers[“X-Mashape-Key”]=“我的API密钥”
request.requestSerializer.headers[“内容类型”]=“应用程序/x-www-form-urlencoded”
request.responseSerializer=JSONResponseSerializer()
请求邮寄(”https://textanalysis.p.mashape.com/segmenter,参数:params,成功:{(response:HTTPResponse)in if let json:AnyObject=response.responseObject{println(\(json)”)},失败:{(error:NSError,response:HTTPResponse?)in println(\(error)})
// {
//结果=“\U4f60\U53eb\U4ec0\U4e48\U540d\U5b57”;
// }
return://我想将json中的“result”作为字符串返回。
}

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

在这段代码中,我发出了一个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

            }
        }
//发出HTTP请求
var post:NSString=“数据=\(数据)”
NSLog(“PostData:%@”,post)
变量url:NSURL=NSURL(字符串:http://domain.com/jsontest.php")!
var postData:NSData=post.dataUsingEncoding(NSASCIIStringEncoding)!
变量postLength:NSString=String(postData.length)
var请求:NSMutableURLRequest=NSMutableURLRequest(URL:URL)
request.HTTPMethod=“POST”
request.HTTPBody=postData
request.setValue(postLength,forHTTPHeaderField:“内容长度”)
request.setValue(“application/x-www-form-urlencoded”,forHTTPHeaderField:“内容类型”)
request.setValue(“application/json”,forHTTPHeaderField:“Accept”)
var REPORNSERROR:NSError?
var响应:nsurresponse?
变量urlData:NSData?=NSURLConnection.sendSynchronousRequest(请求、返回响应:&response、错误:&ResponseError)
if(urlData!=nil){
让res=响应为NSHTTPURLResponse!
NSLog(“响应代码:%ld”,res.statusCode)
如果(res.statusCode>=200&&res.statusCode<300)
{
var responseData:NSString=NSString(数据:urlData!,编码:NSUTF8StringEncoding)!
NSLog(“响应==>%@”,响应数据)
var错误:N错误?
//这里我制作JSON字典
让jsonData:NSDictionary=NSJSONSerialization.JSONObjectWithData(urlData!,选项:NSJSONReadingOptions.MutableContainers,错误:&error)作为NSDictionary
//这样,您就可以以字符串的形式访问JSON字典的值
name.text=jsonData.valueForKey(“名称”)作为NSString
last.text=jsonData.valueForKey(“last”)作为NSString
}
}

希望有帮助:)

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)")
    })
}
也可以看到这个Github问题

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