调用ViewController的方法,从App Delegate推送另一个ViewController

时间:2016-01-29 03:41:22

标签: ios objective-c uiviewcontroller appdelegate

在开始之前,我已经搜索了Stackoverflow以了解如何执行此操作,并且我看到了很多相关的帖子,但没有一个对我有效,我不知道为什么。

所以基本上我有一个loginViewController,在其中,我有一个方法可以调用GoogleSignIn:

- (void)googleTap:(id)sender
{
    [[GIDSignIn sharedInstance] signIn];
}

现在设置GoogleSignIn的方式,该登录呼叫的结果在AppDelegate.m中处理

- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
    // Perform any operations on signed in user here.
    if (!error) {
        NSString *userId = user.userID;                  // For client-side use only!
        NSString *idToken = user.authentication.idToken; // Safe to send to the server
        NSString *name = user.profile.name;
        NSString *email = user.profile.email;

        NSLog(@"Name: %@, User: %@, Token: %@, Email: %@",name, userId, idToken, email);

        // ...
    }
}

在这个AppDelegate方法中,我想从我的loginViewController调用一个方法:

-(void)onSuccessfulLogin{
    NSLog(@"On Successful Login");
    [self.navigationController pushViewController:[collectionViewController new] animated:YES];
}

我尝试了这些答案:Calling UIViewController method from app delegate

want to call ViewController's method from appdelegate

并且调用了NSLog,但新的ViewController从未被推送过......为什么会这样,我怎样才能让它工作?

3 个答案:

答案 0 :(得分:0)

如果这是你的app委托你没有self.navigationController。您可能更改了NavigationController to something like UINavigationController *navigationController = [[UINavigationController alloc] init]的名称。您需要在委托类中为导航控制器设置@property。然后在初始化导航控制器的地方

 UINavigationController *navigationController = [[UINavigationController alloc] init]`
self.navigationController = navigationController// You need this line.


//In your method
    [self.navigationController pushViewController:[collectionViewController new] animated:YES];

答案 1 :(得分:0)

在YourViewController.h(头文件)中声明你的onSuccessfulLogin方法

在(void)signIn:didSignInForUser:withError:方法,在底部放置代码

if ([self.navigationController.viewControllers.lastObject respondsToSelector:@selector(onSuccessfulLogin)]) {
    [((YourViewController *)self.navigationController.viewControllers.lastObject) onSuccessfulLogin];
}

答案 2 :(得分:0)

我一直在想这个错误。您可以将GDSignInDelegate从AppDelegate移动到viewcontroller.h。

然后您只需将 - (void)signIn:didSignInUser:方法移动到ViewController即可。你可以从那里打电话给你的方法!