Reputation: 629
I have a viewController which contains only an imageview. I want to present it whenever there is a loading in the application like fetching data from a webservice. So I have created a function in my loaderViewController as
func showLoading(viewController:UIViewController) {
viewController.presentViewController(LoadingViewController(), animated: false, completion: nil)
}
This is working as expected, when I call this function when desired like below
var loader = LoadingViewController()
loader.showLoading(self)
It show me the viewController with image.
But Now want to dismiss this viewController when desired but I am not able to do so, This is what I have tried so far, I created another function in my LoaderViewController as
func dismissLoader() {
let load = LoadingViewController()
load.dismissViewControllerAnimated(true) {
print("Dismissing Loader view Controller")
}
}
But its not working and the viewController is not disappering from the screen.
Please guide me
Upvotes: 4
Views: 13567
Reputation: 805
In Swift 3 you can do following.
self.dismiss(animated: true)
Upvotes: 5
Reputation: 323
You have to store a link for LoadingViewController
in parent view controller:
var loader: LoadingViewController?
func showLoadingIn(viewController: UIViewController) {
loader = LoadingViewController() // create new instance before presentation
viewController.presentViewController(loader!, animated: false, completion: nil)
}
func dismissLoader() {
loader?.dismissViewControllerAnimated(true) {
print("Dismissing Loader view Controller")
}
}
Upvotes: 1
Reputation: 4859
You don't have to create a new instance of your loader and call dismissViewControllerAnimated(_:Bool)
on it.
Just call
self.dismissViewControllerAnimated(true)
on your viewController
So, your function will be
func dismissLoader() {
dismissViewControllerAnimated(true) {
print("Dismissing Loader view Controller")
}
}
Upvotes: 12
Reputation: 8066
Your code has many flaws. The way you trying to achieve this is not a good practice. However ,If you want a quick fix, and just want to modify your existing method do this,
func dismissLoader() {
self.dismissViewControllerAnimated(true)
print("Dismissing Loader view Controller")
}
And when you're presenting a new LoadingViewController
, keep a reference to it, so you can call above method.
Anyways, above code should work even without you holding a reference, since iOS delegate this method back to it's parent ViewController of it's hierarchy, if there's no presented ViewController available on the called ViewController.
Upvotes: 1
Reputation: 2685
do not make let load = YASLoadingViewController()
everytime, you are creating different controller
Do it once and then use only load
to dismiss or present
Upvotes: 1