I am using this code to access the HTML of a webpage:
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()
However, if the user's internet connection cuts out the application crashes. To combat this, I inserted this block into the code:
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()
This checks to see if an internet connection is available, if not it stops the timer running the automatic database checks and sends the user a message. This method works 80% of the time, however if the internet connection cuts out as the NSURL function is being called, the app still crashes. Is there a way to more effectively monitor the connection with closer to 100% success rate of alerting the user without calling a nil value and crashing the application?
Thank you for your time,
Nick