从UIWebView HTML(JavaScript)调用本机代码(objectiveC)

时间:2014-03-21 21:52:21

标签: ios objective-c uiwebview

我读过

Invoke method in objective c code from HTML code using UIWebView

他们

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

这里,我的代码问题是我没有

UIWebView的委托的shouldStartLoadWithRequest方法,因为我只是直接在AppDelegate中实现UIWebView,如下所示:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{       
    UIWebView *view = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    NSString* path = [[NSBundle mainBundle] pathForResource:@"main" ofType:@"html" inDirectory:@"www"];
    [view loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
    view.scalesPageToFit = NO;
    UIViewController *controller = [[UIViewController alloc] init];
    controller.view = view;

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = controller;
    [self.window makeKeyAndVisible];

    return YES;    
}

我喜欢这种方式,因为代码和文件的结构更简单。

所以我的问题是,是否可以用这种风格实现call-native-from-webView?

或者,我是否需要一个独立的UIWebView Controller / Delegate?

如果可能的话,你能告诉我如何做到这一点的例子吗?

我没有为objectiveC代码和MVC模型做过多少工作,所以如果你告诉我的方式,我们表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:1)

对于设置为webview的委托的任何对象,都会调用webView:shouldStartLoadWithRequest:navigationType:方法。