Chris
Chris

Reputation: 269

Cancelling a view controller from loading if a URL cannot load - Swift 4

When a view controller is being loaded it has to obtain a JSON file via a URL. If the internet is down I would like it to cancel loading the view controller. Here is the code so far and I know it is wrong in the catch, but it give you an idea of what I need to do. So overall, should I be using a different override than viewDidLoad() since it "did" load?

 override func viewDidLoad() {

        var jsonText = ""
        if let url = URL(string: "http://thedomain.com/eventlistjson_r2.asp") {
            do {
                jsonText = try String( contentsOf: url,encoding: .utf8)
            } catch {
                // contents could not be loaded
                print(error)
                super.dismiss(animated: true)
            }
        } else {
            // the URL was bad!
            print("the URL was bad")
        }
}

Upvotes: 0

Views: 440

Answers (2)

radetara
radetara

Reputation: 36

If your view controller is meaningless without data, maybe you should consider trying to reach for data first and then decide whether to push/present UIViewController or not. In that case whoever is instantiating view controller is trying to retrieve JSON first, and only in case of success instantiating and passing data to mentioned view controller.

Second option is that your view controller checks for data itself and in case none found, present user with information before dismissing itself. You can f.e. achieve that by:

  1. Showing information directly in view of your view controller (then viewDidLoad() would be suitable place for that) and leaving user possibility to navigate back by pressing back button.
  2. Presenting UIAlertController, where your view controller would dismiss itself on pressing alert confirmation button.

Anyway, loading and dismissing view controller without any feedback raises a flag of poor UX or design.

If you provide us with more detail on the logic behind and expected behavior, maybe I can try to offer better answer, but I believe that any of the approaches above would be a good start.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

This

jsonText = try String( contentsOf: url,encoding: .utf8)

blocks the main thread so when user clicks a button on the vc that push that vc , it' ll seem to the user that the app is not functioning , what you should do is inside that mainVC

// add loading 
// make the call in a background thread such as URLSession.shared or Alamofire
// then decide inside the callback whether to proceed with push/segue or stay in that mainVC

in addition a dismiss with

self.dismiss(animated: true) // not super 

Upvotes: 0

Related Questions