Dismissing ViewController Scenario

时间:2016-02-03 03:11:41

标签: ios swift uiviewcontroller swift2

I am new to Swift programming. I am stuck in one scenario. When my app loads, the first screen gets in ViewController1 user's latitude and longitude and then gets the data from a backend API and loads the data in a table view controller. This code of getting user's location and loading table view controller is in ViewDidLoad method. In this ViewController1, I have a button when tapped, I am presenting a view controller (Which is embedded in a navigation controller) modally. The following lines of code I am using to present this new ViewController (ViewController2).

let VC2 = self.storyboard?.instantiateViewControllerWithIdentifier("NewVC2") as! NewVC2
            let navController = UINavigationController(rootViewController: VC2)
            VC2.delegate = self
            self.presentViewController(navController, animated: true, completion: nil)

When I close the ViewController2 by saying self.dismissViewController, it closes and when the control comes back to ViewController1, ViewDidLoad is executed again and all the code of invoking backend API and getting user's location is getting invoked. So, for passing data back from ViewController2 on dismissing it, I used the delegate pattern. Created a protocol and defined a method in this protocol.

protocol ViewControllerClosedDelegate {
    func isViewControllerClosed(closed: Bool);
}

defined the object of delegate in ViewController2.
var delegate: ViewControllerClosedDelegate! = nil

and added the following code while dismissing ViewController2.

delegate.isViewControllerClosed(true)
self.dismissViewControllerAnimated(true, completion: nil)

made the ViewController1 to implement this ViewControllerClosedDelegate and added the following function.

func isViewControllerClosed(closed: Bool) {
        self.isFromClosedVC = closed
        print(isFromClosedVC)
    }

isFromClosedVC is a global variable defined ViewController1.

the value is printing correctly (true in this case) as being passed from ViewController2 when it is dismissed but when I try to print this in ViewDidLoad, it is being printed as false. I thought of getting this value from ViewController2, and if it is true, not to execute the code to get users location and data from backend API.

Basically, I am trying to get the user's location and getting the data from backend API once and update my table view only on Swipe to refresh. How do I achieve this? Please help.

Thank you. Raj

0 个答案:

没有答案
相关问题