在URL方案OpenURL之后从AppDelegate调用ViewController方法

use*_*803 2 iphone xcode objective-c uiviewcontroller ios

我试图LoadWebpage从AppDelegate.m 调用ViewController.m中的函数.

我已经使用URL方案启用了我的应用程序,以便Safari中的"urlscheme://?querystring"链接打开我的应用程序.我在AppDelegate中捕获url方案(我可以通过记录这可以告诉它这是有效的)并且想用querystring填充一个全局变量然后调用我的LoadWebPage方法,以便视图控制器可以使用全局变量并打开所请求的网站在WebView控件中.

我正在学习本教程.

这是AppDelegate.m:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    NSLog(@"Calling Application Bundle ID: %@", sourceApplication);
    NSLog(@"URL scheme:%@", [url scheme]);
    NSLog(@"URL query:%@", [url query]);
    URLString = (NSString *)[url query]; //extern variable

    [self.ViewController loadWebpage];
    return YES;

}
Run Code Online (Sandbox Code Playgroud)

在ViewController.m中:

- (void)LoadWebpage{

    NSString *strURL=URLString;  //more logic will be required to get the appropriate url from the query string.
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [self.webview loadRequest:urlRequest];

}
Run Code Online (Sandbox Code Playgroud)

但该行[self.ViewController loadWebpage];有一个错误"Property'ViewController'找不到'AppDelegate'类型的对象".

我猜我需要合成对open viewcontroller的引用,但我找不到有关如何执行此操作的信息.这是处理这个问题的最佳方法吗?

编辑:根据Yan的评论,我尝试添加

ViewController* mainController = (ViewController*)  self.window.rootViewController;
[mainController LoadWebpage];
Run Code Online (Sandbox Code Playgroud)

而不是[self.ViewController loadWebpage];它只是用lldb结束调试?

Axe*_*eva 6

我建议让View Controller注册以在应用启动时收到通知,而不是试图在视图控制器中触发AppDelegate.然后,您可以检查您在AppDelegate中设置的变量并做出相应的反应.

例如:

YourViewController.m:

- (void)viewDidLoad {
    [super viewDidLoad];

    // This notification is sent the first time the app launches
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(applicationBecameActive:)
                                                 name: UIApplicationDidBecomeActiveNotification
                                               object: nil];

    // This notification is sent when the app resumes from the background
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(applicationEnteredForeground:)
                                                 name: UIApplicationWillEnterForegroundNotification
                                               object: nil];
}
Run Code Online (Sandbox Code Playgroud)