我在Swift中使用以下函数连接到服务器上的PHP脚本,然后处理我的请求:
func pushtoserveronclick() {
var URL: NSURL = NSURL(string: "http://someurl.com/")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
var bodyData = "data=something&version=\(appVersion)"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(response)
}
}
当我运行应用程序时,我将其作为响应返回:
<NSHTTPURLResponse: 0x14e53170> { URL: http://someurl.com/ } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "text/html";
Date = "Fri, 05 Dec 2014 06:23:23 GMT";
"Keep-Alive" = "timeout=2, max=100";
Server = Apache;
"Transfer-Encoding" = Identity;
如何获取正在返回的状态代码,以便我可以对其进行检查并判断它是否是连接问题?
答案 0 :(得分:2)
NSURLConnection.sendAsynchronousRequest
在类型签名中使用NSURLResponse
,但只要您通过HTTP进行连接,该实例就是(通常)NSHTTPURLResponse
,其{{1} }}。
您可以通过以下方式检查和投射:
statusCode