Search code examples
iosobjective-cuiviewcontrolleruinavigationcontroller

How to present UIViewController from viewController's view


I'm using the view of a UITableViewController in a UIViewController as can be seen below:

UITableViewController *tvc = [[UITableViewController alloc] init];
[self.view addSubview:tvc.view];

Now, inside this UITableViewController I'd like to be able to present a SFSafariViewController if necessary. I wrote the code below:

if (showLink) {
    SFSafariViewController *sfsvc = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com"]];
    [self.presentingViewController.navigationController pushViewController:sfsvc animated:YES];
}

Whenever I run this, I get the following error in the console and nothing happens:

[Warning] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<SFSafariViewController: 0x7f8aef82a600>)

Any ideas how I can solve this?


Solution

  • Using rootViewController to push SFSafariViewController is a solution for you in this case. Try my code below

    if (showLink) {
        SFSafariViewController *sfsvc = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com"]];
        UIViewController *rootViewController = UIApplication.sharedApplication.delegate.window;
        [rootViewController.navigationController pushViewController:sfsvc animated:YES];
    }