1. 程式人生 > >ios 開發之 原生+html5混合開發 [[ 方法互調 ]]

ios 開發之 原生+html5混合開發 [[ 方法互調 ]]


一原生應用修改 html
原生應用呼叫 js程式碼還是比較簡單的,就是藉助UIWebView 的代理方法.

首先,載入 index.html - (void)viewDidLoad
{
    [superviewDidLoad]; NSURL*url = [[NSBundlemainBundle]URLForResource:@"index"withExtension:@"html"];
    
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
    [
self.webViewloadRequest:request];
} 其次,實現 webView 代理 - (void)webViewDidFinishLoad:(nonnullUIWebView*)webView
{
  //當載入完成的時候就可以修改 html 的內容   //比如獲取 img,p,button 等標籤   NSString*str = @"var img = document.getElementsByTagName('img')[0];";   //增刪改查等   NSString*str1 = @"img.remove();";   //最主要的方法,通過此方法,就可以修改載入的頁面啦   [webViewstringByEvaluatingJavaScriptFromString
:str];   [webView stringByEvaluatingJavaScriptFromString:str1]; }


二.html 呼叫原生方法 
通過此方法,就可以達到呼叫系統資源的目的,比如相簿,相機等

首先,在 index.html 中新增單機事件 <html> <head> <meta charset="UTF-8"> </head> <body>       <button onclick="btnClick();">訪問相簿</button> <script>
function btnClick(){              window.location.href ='lyl://btnClick';           } </script> </body> </html> 接著,在 viewDidLoad里加載index.html - (void)viewDidLoad
{
    [
superviewDidLoad];
   
  
  NSURL *url = [[NSBundlemainBundle]URLForResource:@"index"withExtension:@"html"];
  
  NSURLRequest *request = [NSURLRequestrequestWithURL:url];
    [
self.webViewloadRequest:request]; } //實現代理 - (BOOL)webView:(nonnullUIWebView*)webView shouldStartLoadWithRequest:(nonnullNSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
   
NSString *url = request.URL.absoluteString;
   
NSRange range = [url rangeOfString:@"lyl://"];     NSUIntegerlocation = range.location; if(location != NSNotFound)
   {
        //將url 處理得到方法名btnClick' NSString*str = [url substringFromIndex:location + range.length];
        //轉換成方法,然後呼叫
 SELsel = NSSelectorFromString(str);
        [
selfperformSelector:selwithObject:nil];
    }
    return YES } //實現方法 -(void)btnClick
{
NSLog(@“我點,我點"); }