我正在尝试从AppDelegate.m调用ViewController.m中的函数LoadWebpage
。
我已使用 URL 方案启用了我的应用程序,以便 Safari 中的"urlscheme://?querystring"链接打开我的应用程序。 我正在 AppDelegate 中捕获 url 方案(我可以通过日志记录来判断这是有效的),并希望用查询字符串填充全局变量,然后调用我的 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];
行有一个错误"在类型为'AppDelegate'的对象上找不到属性'视图控制器'"。
我猜我需要合成对打开的视图控制器的引用,但我找不到有关如何执行此操作的信息。 这是处理这个问题的最佳方法吗?
编辑:根据Yan下面的评论,我尝试添加
ViewController* mainController = (ViewController*) self.window.rootViewController;
[mainController LoadWebpage];
而不是[self.ViewController loadWebpage];
,但它只是用lldb结束调试?
与其尝试让 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];
}
对于那些想要在 Swift 中使用它的人!
首先,创建要发送数据的通知中心发布方法(在 Swift 2.0 中 - NSNotification Center):
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NOTIFICATION_NAME"), object: nil)
return true
}
在要接收数据的 ViewController 类中,在 super.viewDidLoad() 中添加以下内容:
NotificationCenter.default.addObserver(self,selector: #selector(self.YOUR_METHOD_NAME),
name: NSNotification.Name(rawValue: "NOTIFICATION_NAME"),
object: nil)
以及您要调用的方法:
func YOUR_METHOD_NAME(notification: NSNotification) {
// Your method calling, or what you want to do with received data
}