如何持续监控NSURL连接以便在互联网连接中断

时间:2015-12-17 01:42:32

标签: ios swift nsurl


我正在使用此代码访问网页的HTML:

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()

但是,如果用户的互联网连接中断了应用程序崩溃。为了解决这个问题,我将这个块插入到代码中:

if Reachability.isConnectedToNetwork() != true {
        self.sendAlert("Error", message: "You are not connected to the internet")
        timer.invalidate()
        return
    }
let myUrl = NSURL(string: "http://www.casacorazon.org/ios.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()

这将检查互联网连接是否可用,如果没有,它会停止运行自动数据库检查的计时器并向用户发送消息。此方法在80%的时间内都有效,但是如果在调用NSURL函数时互联网连接中断,则应用程序仍会崩溃。有没有办法更有效地监控连接,以更接近100%的成功率提醒用户而不调用零值并使应用程序崩溃?
谢谢你的时间,
尼克

0 个答案:

没有答案