我的UIWebView
中有ViewController
,我希望在UIApplicationDelegate
传递网址时更新,例如
myApp://?changeWebView=newstuff
我根据传入的数据构建新网址但我无法弄清如何更新我的UIWebView
我在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]);
NSLog(@"URL hash: %@", [url fragment]);
NSURL *newURL = [NSURL URLWithString:@"URL constructed with pieces of passed URL data"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:newURL];
//now I want to update the UIWebview defined in my ViewController.h
return YES;
}
答案 0 :(得分:2)
您可以使用webView
loadRequest
中加载请求
[self.myWebView loadRequest:requestObj];
把这一行放在你的代码中
您可以发布通知,让您了解可以加载webview的视图控制器。
- (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]);
NSLog(@"URL hash: %@", [url fragment]);
NSURL *newURL = [NSURL URLWithString:@"URL constructed with pieces of passed URL data"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:newURL];
//Post Notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"loadRequest"
object:nil
userInfo:@{@"requestObj":requestObj}];
return YES;
}
现在在viewController中添加通知观察器
-(void)viewDidLoad{
//Add observer for notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"loadRequest" object:nil];
}
将此方法写入webView
ViewController
加载请求
- (void)receiveEvent:(NSNotification *)notification {
// handle event
NSURLRequest *requestObj = notification.userInfo[@"requestObj"];
[self.myWebView loadRequest:requestObj];
}
答案 1 :(得分:0)
对于初学者,由于您在app委托中执行此操作,因此您不知道将分配具有Web视图的视图控制器。因此,您有几种不同的选择。
@property (nonatomic, weak) UIViewController *viewController;
)。加载视图控制器时,使用Web视图将此属性设置为视图控制器,以便在应用程序委托中对其进行引用。NSNotification
。这样做的好处是您可能希望将此URL发送到许多不同的类,NSNotification允许这样做。每个类都可以单独添加自己作为通知的观察者。这是一个例子:Send and receive messages through NSNotificationCenter in Objective-C?