1


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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
iamnickpitoniak
  • 227
  • 1
  • 4
  • 11
  • Use do/try/catch (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html). Related SO question http://stackoverflow.com/questions/31030366/http-post-error-handling-in-swift-2 – Anthony Kong Dec 17 '15 at 01:57
  • When you say "the app crashes", what does that mean? Please post the exact error message and backtrace. – jtbandes Dec 17 '15 at 02:01
  • @iamnickpitoniak you need to replace all occurrences of forced unwrapping and use guard or if let. try adding "guard let data = data where error == nil else { return}" – Leo Dabus Dec 17 '15 at 03:02
  • Instead of this inefficient pinging, look into using `Reachability`. – rmaddy Dec 17 '15 at 03:19
  • @AnthonyKong Is there a way to make a simple try/catch statement wrapping the whole function? I have spent a while reading tutorials, and I am still shaky on calling individual errors. Is there a way to do something like: do { NSURL connection } catch { present user with error and terminate NSURL interval } ? Thank you very much for the assistance – iamnickpitoniak Dec 17 '15 at 15:29

0 Answers0