我试图在用php编写的网站上编码一个简单的字符串:
json_encode("str"); echo json_encode("str");
在斯威夫特,我将如何取回那根绳子。我现在有一个报告HTTPBody的功能。
func buttonAction(sender:UIButton!)
{
var request = NSMutableURLRequest(URL: NSURL(string: myUrlWhereThePHPCodeWasWritten), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
let jsonString = ""
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
request.HTTPMethod = "GET"
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(response)")
} else {
println("No HTTP response")
}
}
我如何让它打印出"str“本身。我是一个菜鸟,基本上是试图创建一个hello world版本的这个过程。
发布于 2014-10-21 08:11:50
有几个想法:
sendSynchronousRequest
,则应该将NSData
作为返回值:
如果让NSURLConnection.sendSynchronousRequest(request,= returningResponse:&response,error:&error) { //如果JSON : NSError?如果让responseObject =NSJSONSerialization.JSONObjectWithData(数据、选项:零、错误:&parseError)作为?NSDictionary { println("string = (responseObject)") } else { println("parseError = (parseError)") } //如果简单字符串/ let string =NSString(数据:数据,编码: NSUTF8StringEncoding) // println("string = ( string )") } as {println(“parseError=(ParseError)”)}}如果让httpResponse =响应为?NSHTTPURLResponse {println(“NSHTTPURLResponse:(响应)”){println(“没有HTTP响应”)}sendSynchronousRequest
。或者,至少不要从主线程调用它。使用异步方法,例如:
NSURLConnection.sendAsynchronousRequest(request,队列:0){响应、数据、如果让httpResponse = response?NSHTTPURLResponse {println(“NSHTTPURLResponse:(response)") {println(”没有HTTP响应“)}如果数据!= nil {/如果JSON : NSError?如果让responseObject =NSJSONSerialization.JSONObjectWithData(数据、选项:零、错误:&parseError)作为?NSDictionary { println("string = (responseObject)") } else { println("parseError = (parseError)") } // if简单字符串/ let string =NSString(数据:编码: NSUTF8StringEncoding) // println("string = ( string )") }if{println(“parseError=(ParseError)”)}{println(“错误=(错误)”)}
或者使用NSURLSession.sharedSession().dataTaskWithURL(...)
之类的东西。顺便说一下,在上面的两个例子中,我在解析JSON时都使用了as NSDictionary
。如果要生成JSON数组,则将其更改为as NSArray
。
注意:我从PHP推断出您想要生成一个有效的json_encode
响应。但您不能只使用json_encode
字符串。通常,您可以使用json_encode(["key" => "string"])
来生成字典,或者使用json_encode(["string"])
来生成数组。
https://stackoverflow.com/questions/26490837
复制相似问题