目前我的 iOS (Swift) 端的代码正在向我的 Node 服务器发送 POST 请求,当它到达服务器时返回状态代码 200。
问题: 我想做的是将数据返回到设备,在本例中发送回“nice”。
Node 监听 Post 请求:
app.post('/test.json', function (req, res){
console.log("Hit!");
res.send('nice');
});
和 swift :
override func viewDidLoad() {
super.viewDidLoad()
// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://serverlocation.com/path")!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// look at the response
println("The response: \(response)")
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
}
最佳答案
要获取响应主体,您需要存储方法 sendSynchronousRequest
返回的数据,然后将其设为字符串,因为 sendSynchronousRequest
返回 NSData 对象的实例。< br/>
它会是这样的:
let body = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
let bodyStr = NSString(data: body!, encoding: NSUTF8StringEncoding)
print(bodyStr)
也就是说,我建议不要对服务器使用同步请求,这会阻塞 UI 直到完成,这可能会让最终用户感到厌烦。要使其成为异步请求,您可以将方法 + sendSynchronousRequest:returningResponse:error:
更改为方法 + connectionWithRequest:delegate:
。然后使 View Controller 成为您的委托(delegate)并在其中实现方法:
- 连接:didReceiveResponse:
- 连接:didReceiveData:
捕获响应并处理其中的数据。也不要忘记将 NSURLConnectionDataDelegate
添加到 ViewController
或您设置为委托(delegate)的任何类的声明中。
关于评论中的问题:
Would it be better to send these requests from the ViewController or AppDelegate?
将此代码放在哪里取决于您要检索的数据。在 AppDelegate
中放置一些东西通常是一个坏主意,除非无论 View 中发生什么,无论发生什么,你都想做一些事情。
将它放在 ViewController
上将是一个好主意,如果它正在检索与您将要在此特定 View 中显示的内容相关的信息。否则,如果信息与数据结构之类的东西更相关,则创建另一个从服务器检索数据并以适合此数据结构的形式处理数据的类会更有意义。
关于ios - 将数据从 Node 服务器发送回 iOS 设备(使用 Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144951/