我正在尝试从AppDelegate.m调用ViewController.m中的函数LoadWebpage
。
我已经使用URL方案启用了我的应用,以便" urlscheme://?querystring" Safari中的链接打开我的应用程序。我在AppDelegate中捕获url方案(我可以通过记录这可以告诉它这是有效的)并且想用查询字符串填充一个全局变量,然后调用我的LoadWebPage
方法,以便视图控制器可以使用全局变量并在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];
行有一个错误"属性' ViewController'没有找到类型' AppDelegate'"。
我猜我需要合成对open opencontroller的引用,但我无法找到有关如何执行此操作的信息。这是解决这个问题的最好方法吗?
编辑:根据Yan的评论,我尝试添加
ViewController* mainController = (ViewController*) self.window.rootViewController;
[mainController LoadWebpage];
而不是[self.ViewController loadWebpage];
,而只是用lldb结束调试?
答案 0 :(得分: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];
}
答案 1 :(得分:2)
对于那些在Swift中想要它的人来说!
首先,创建要发送数据的NotificationCenter post方法(在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
}