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

 工农大路店NOKIA客户服务中心 发布于 2022-12-10 10:31

我试图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;

}

在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];

}

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

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

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

ViewController* mainController = (ViewController*)  self.window.rootViewController;
[mainController LoadWebpage];

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

1 个回答
  • 我建议让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];
    }
    

    2022-12-11 02:56 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有