UIwebview中的Html表单发送回ios?

时间:2014-01-14 09:08:56

标签: objective-c uiwebview

我正在尝试在HTML表单和ios之间传递信息我尝试了javascrip但它不起作用?

        // Init Web View
    UIWebView *webView;
    webView = [[UIWebView alloc] initWithFrame:boundsRect];
    webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    webView.scalesPageToFit = YES;
    webView.contentMode = UIViewContentModeCenter;
    webView.multipleTouchEnabled = NO;
    webView.userInteractionEnabled = YES;
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    [self addSubview:webView];
    NSString *testArrayString = [webView stringByEvaluatingJavaScriptFromString:@"testString"];
    NSArray *testArray = [testArrayString componentsSeparatedByString:@"#"];
    NSLog(@"%@", testArray);
    [webView release];
    return self;

任何想法?

---- ---- EDIT

好的家伙,如果您只想将表单中的数据传递给ios应用程序,那么只对您的webview执行此操作

[webView setDelegate:self];

然后,您可以在程序标记中实现此方法

像:

    -(void)webViewDidFinishLoad:(UIWebView *) webView {

//implement code to do here

}

如果你想捕获一个只是做一个webview的shouldStartWithRequest,就像这样:

    -(BOOL)webView:(UIwebView *) webView shouStartWithRequest:(NSURLRequest *)request  navigationType:(UIWebViewNavigationType)navigation{


//implement code to do afeter the user click the form  don't forget to return YES or NO because it is a BOOL 

}

这就是我如何解决它的任何问题,请告诉我,我尽力帮助

1 个答案:

答案 0 :(得分:1)

要从UIWebView传递数据并返回到Objective-C运行时,您需要实现UIWebViewDelegates webView:shouldStartLoadingWithRequest:并将表单数据作为参数传递到URL中。如果你用f.ex这样的方案制作所有的URL。 my-app://?parameter1=value1&parameter2=value2,您可以轻松过滤出网页视图无法加载的网址,并返回NO。

编辑:

添加了示例代码。

- (void)initWebView
{
  UIWebView *webView;
  webView = [[UIWebView alloc] initWithFrame:boundsRect];
  webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  webView.scalesPageToFit = YES;
  webView.contentMode = UIViewContentModeCenter;
  webView.multipleTouchEnabled = NO;
  webView.userInteractionEnabled = YES;
  webView.delegate = self;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  NSURL *url = request.URL;
  if ([url.scheme isEqualToString:@"http://"]) {
    return YES;
  }

  else if ([url.scheme isEqualToString:@"my-app://"]){
    // Process data from form
    return NO;
  }
  return YES;
}

EDIT2:您正在初始化代码中发布Web视图。这可以防止在加载form-url时调用delegate-method

EDIT3:有关更多代码示例,请参阅此问题:Invoke method in objective c code from HTML code using UIWebView