iOS: 在Object-C中監聽javascript事件( Javascript communicating back with Objective-C code)


iOS開發之Objective-C與JavaScript交互操作 中我們可以通過stringByEvaluatingJavaScriptFromString 去實現在obj-C中獲取到相關節點屬性,添加javascript代碼等功能。但是我們如何監聽到javascript的響應事件呢。在MAC OS中有效的API去實現,但iPhone沒有,但我們有一個技巧途徑:

大概思路是:在JavaScript事件響應時,通過設置document.location,這會引發webview的一個delegate方法,從而實現發送通知的效果,即達到監聽的目的。

1、在javascript與webView之間定一個協議約定:

     myapp:myfunction:myparam1:myparam2

2、在javascript中添加代碼:

document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;

3、在webView的delegate方法webView:shouldStartLoadWithRequest:navigationType:  添加

- (BOOL)webView:(UIWebView *)webView2 
    shouldStartLoadWithRequest:(NSURLRequest *)request 
    navigationType:(UIWebViewNavigationType)navigationType {
 
    NSString *requestString = [[request URL] absoluteString];
    NSArray *components = [requestString componentsSeparatedByString:@":"];
 
    if ([components count] > 1 && 
        [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"]) 
        {
 
            NSLog([components objectAtIndex:2]); // param1
            NSLog([components objectAtIndex:3]); // param2
            // Call your method in Objective-C method using the above...
        }
        return NO;
    }
 
    return YES; // Return YES to make sure regular navigation works as expected.
}

 

 

check:http://stackoverflow.com/questions/5671742/send-a-notification-from-javascript-in-uiwebview-to-objectivec

http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM