我正在使用NSURL从网站上抓取HTML。问题是,如果在NSURL请求期间互联网中断,应用程序崩溃。
代码:
let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(responseString!)"
}
}
}
task.resume()
我可以在使用此代码进行NSURL连接之前检查互联网连接,但是在操作过程中仍有可能断开互联网:
在NSURL之前检查网络连接的代码:
let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(responseString!)"
}
}
}
task.resume()
为了解决这个问题我已经研究过使用try / catch操作,但是我没有成功构建一个不会给我错误的运气。有没有办法将整个NSURL操作包装在一个捕获任何错误的巨型try / catch中?我正在思考这方面的问题,但它不起作用:
代码:
let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(responseString!)"
}
}
}
task.resume()
} catch {
timer.invalidate
sendAlert("Error", message: "You are not connected to the internet")
}
答案 0 :(得分:4)
!
发音的正确方法是"我发誓我的节目生活。"因为这就是你正在做的事情。为什么你觉得必须使用!
?使用guard-let
为您解决所有问题:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
guard error == nil else {
print("Error: \(error)")
return
}
guard let data = data else {
fatalError("error was nil, but no data. This should never happen")
}
guard let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) else {
print("Couldn't decode data")
return
}
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(responseString)"
}
}
答案 1 :(得分:1)
如果你知道100%有一个值,你应该只强制解包变量,否则你会导致你的应用崩溃。如果您需要更多相关信息,请查看The Swift Programming Language guide
的可选链接部分检查
以下代码适合您。
let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
if let responseData = data {
let responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
print("Response: \(responseString!)")
}
}
}
}
task.resume()
在处理您的互联网连接失败方面,您应该检查关闭时发回的响应,并决定您要采取的行动方案。
if let httpResponse = response as? NSHTTPURLResponse {
println("error \(httpResponse.statusCode)")
}