2014-01-14 34 views
1

我想通過HTML表單和ios之間的信息我試過javascrip但它不工作?UIwebview中的HTML表單發送回ios?

 // 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; 

有什麼想法嗎?

---- ----編輯

玉傢伙,如果只想要使從表單數據傳遞給iOS應用程序,你只能這樣做,以你的WebView

[webView setDelegate:self]; 

然後你可以實現這個方法在你的程序,標誌着

,如:

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

//implement code to do here 

} 

,如果你想捕捉對於j烏斯季做的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 

} 

是我如何解決它的任何問題,請不要告訴我,我盡我所能來幫助

+0

'stringByEvaluatingJavaScriptFromString:'希望你傳遞一個JavaScript代碼段,它將在網絡視圖的上下文中進行評估。 'testString'沒有意義,它不是JavaScript,所以什麼也沒有發生。 – Jasarien

回答

1

從UIWebView的傳遞數據和回你的Objective-C運行,您需要實現UIWebViewDelegates webView:shouldStartLoadingWithRequest:並將您的表單數據作爲參數傳遞給URL。如果你用f.ex這樣的方案製作你的所有URL。 my-app://?parameter1=value1&parameter2=value2,你可以很容易地過濾網頁視圖不應該加載的URL,並返回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; 
} 

編輯2:你在初始化代碼中發佈web視圖。這可以防止委託-方法被調用時,正在加載的形式,網址

EDIT3:中查看代碼示例這個問題:Invoke method in objective c code from HTML code using UIWebView

+0

我在哪裏可以實現 –

+0

我的問題是HTMl文件是本地的 –

+0

這仍然有效。本地html用''file://''''url-scheme加載請求。要將數據從表單發送到應用程序,只需在html文件中構建一個url,該url包含要傳遞給Objective-C運行時的數據,並確保Web視圖嘗試加載該url 。無論是通過點擊一個錨標記,或與JavaScript設置'''window.location''' –