gpt4 book ai didi

ios - 在 URL Scheme OpenURL 之后从 AppDelegate 调用 ViewController 方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:38 27 4
gpt4 key购买 nike

我正在尝试从 AppDelegate.m 调用 ViewController.m 中的函数 LoadWebpage

我已使用 URL Scheme 启用我的应用程序,以便 Safari 中的“urlscheme://?querystring”链接打开我的应用程序。我正在 AppDelegate 中捕获 url 方案(我可以通过日志记录知道这是有效的)并且想用查询字符串填充全局变量然后调用我的 LoadWebPage 方法以便 View Controller 可以使用全局变量并在 WebView 控件中打开请求的网站。

我正在关注 this tutorial .

这是 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]; 有一个错误“在‘AppDelegate’类型的对象上找不到属性‘ViewController’”。

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

编辑:根据下面严的评论,我尝试添加

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

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

最佳答案

与其尝试让 AppDelegate 在您的 View Controller 中触发某些东西,我建议让 View Controller 注册以在应用程序启动时接收通知。然后您可以检查您在 AppDelegate 中设置的变量并做出相应的 react 。

例如:

你的ViewController.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];
}

关于ios - 在 URL Scheme OpenURL 之后从 AppDelegate 调用 ViewController 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27068473/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com