检查NSURL是否在Swift中返回404

时间:2015-01-08 10:34:48

标签: ios objective-c swift http-status-code-404 nsurl

依赖本主题中的主题: Check if NSURL returns 404

如何在Swift中检查页面是否返回404?

我是一名新的iOS开发人员,而且我没有足够的知识将Objective-C转换为Swift(我已经开始使用Swift ..)

有没有人可以帮我弄清楚如何在Swift中执行此操作?

非常感谢

1 个答案:

答案 0 :(得分:0)

let urlPath: String = "www.aaaa.com/test"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
var error: NSErrorPointer = nil
var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err: NSError
println(response)
//response.statusCode is what you want
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("Synchronous\(jsonResult)")

您可以查看:

if response.statuCode == 200

或者

if response.statuCode == 404

希望这会有所帮助.. :)