iOS+JavaScriptCore.framework的基本使用(二)

實際使用

繼續上篇iOS+JavaScriptCore.framework的基本使用(一)
示例代碼:(YYJavaScriopCoreDemo)
.
使用場景:加載一個web網頁JSCallOC.html,點擊網頁上的選擇圖片按鈕,選擇圖片, 根據選擇的狀態更新相關提示。

JSCallOC.gif
  1. 思路:
    1. 加載完網頁時,獲取javascript的運行環境 self.jsContext,并進行相關設置
    2. JS調用OC方法takePicture: 點擊網頁的“Select Picture”按鈕時,調用 JSOCViewController 的方法 -(void)takePicture;
    3. OC調用JS方法showResult: 選擇完圖片后,OC調用JS的修改紅色文字的方法

  2. 代碼實現

    1. 網頁處理
      <!doctype html>
      <html>
      <head>

           <title>JSCallOC</title>
           
           <script type="text/javascript">
               <!--??????1.showResult為js中定義的方法-->
               function showResult(resultStr)
               {
                   document.getElementById("result").innerText = resultStr;
               }
           
           </script>
           
       </head>
      
       <body >
      
           <div id="div-a">
               <center>
                   
                   <div  width="100" height="100" >
                       <font size="5" color="red"> <b id="result"> select </b> </font>
                   </div>
                   
                   <!--??????2.ocObject為一個oc對象,takePicture是一個遵守了JSExport協議的對象方法,因為只有遵守JSExport協議的OC方法才能被js調用-->
                   <input id="tpBtn" type="button" value="Select Picture" onclick="ocObject.takePicture();"  />
                   <br/>
                   <br/>
               </center>
           </div>
           
       </body>
      
       </html>
      
    2. oc 處理

      1. 加載網頁
        - (void)viewDidLoad {
        [super viewDidLoad];

            NSURL *url = [[NSBundle mainBundle] URLForResource:@"JSOC.html" withExtension:nil];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            self.webview.delegate = self;
            [self.webview loadRequest:request];
        }
        
      2. 網頁加載完后進行相關處理
        - (void)webViewDidFinishLoad:(UIWebView *)webView{

            // 獲取網頁標題
            self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
            
            // 2.1. 獲取js執行環境
            self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
            
            // 2.1 傳遞js所需要的對象
            self.jsContext[@"ocObject"] = self;
            self.jsContext.exceptionHandler = ^(JSContext *con, JSValue *exception) {
                
                con.exception = exception;
                
                NSLog(@"%@", exception);
            };
        }
        
      3. 自定義JSExport子協議JSOCViewControllerExport,控制器JSOCViewController遵守并實現協議,以供網頁調用,查看上面的網頁標簽 <input id="tpBtn" type="button" value="Select Picture" onclick="ocObject.takePicture();" />
        //3.1.自定義協議
        @protocol JSOCViewControllerExport <JSExport>
        - (void)takePicture;
        @end

            //3.2.遵守協議
            @interface JSOCViewController : UIViewController<JSOCViewControllerExport>
            @end
        
            @implementation JSOCViewController
            //3.3.實現協議
            - (void)takePicture{
                
                // 運行時發現一個問題:會報一下問題:This application is modifying the autolayout engine from a background thread
                // 然后,發現不在主線程,但UI修改需在主線程運行,所以有了下面的GCD
                NSLog(@"%@",[NSThread currentThread]);
                
                __weak typeof (self) weakSelf = self;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    // 對話框提示
                    UIAlertController *actionSheet = [[UIAlertController alloc]init];
                    
                    UIAlertAction *act0 = [UIAlertAction actionWithTitle:@"OC拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                        
                        if (![UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]) {
                            // OC 調用 JS 方法
                            JSValue *updateFunc = self.jsContext[@"showResult"];
                            [updateFunc callWithArguments:@[@"相機不支持"]];
                            return ;
                        }
                        
                        //資源類型為照相機
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.delegate = weakSelf;
                        picker.allowsEditing = YES;
                        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                        [weakSelf presentViewController:picker animated:YES completion:nil];
                    }];
                    
                    UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"OC相冊" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                        //資源類型為圖片庫
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.delegate = weakSelf;
                        picker.allowsEditing = YES;
                        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                        [weakSelf presentViewController:picker animated:YES completion:nil];
                    }];
                    
                    UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    [actionSheet addAction:act0];
                    [actionSheet addAction:act1];
                    [actionSheet addAction:act2];
                    
                    [weakSelf presentViewController:actionSheet animated:YES completion:nil];
                    
                });
                
            }
        
            @end
        
      4. 調用js方法修改相關文字提示

        -(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
            
            // 4.1. OC 調用 JS 方法
            JSValue *updateFunc = self.jsContext[@"showResult"];
            [updateFunc callWithArguments:@[@"已選擇"]];
            
            //關閉相冊界面
            [picker dismissViewControllerAnimated:YES completion:nil];
        }
        
        - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
            
            // 4.2. OC 調用 JS 方法
            JSValue *updateFunc = self.jsContext[@"showResult"];
            [updateFunc callWithArguments:@[@"取消選擇"]];
            
            //關閉相冊界面
            [picker dismissViewControllerAnimated:YES completion:nil];
        }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 項目中涉及OC與網頁的交互,查找資料時看到了JavaScriptCore.framework,就對照文章ios7 ...
    YaoYaoX閱讀 2,387評論 7 11
  • 隨著H5技術的興起,在iOS開發過程中,難免會遇到原生應用需要和H5頁面交互的問題。其中會涉及方法調用及參數傳值等...
    Chris_js閱讀 3,120評論 1 8
  • 前提:在iOS控制器中加載UIWebView,設置代理,遵守UIWebViewDelegate協議。 一、iOS調...
    大沖哥閱讀 1,254評論 0 8
  • <一>iOS與H5交互 在iOS控制器中加載UIWebView,設置代理,遵守UIWebViewDelegate協...
    qui丶MyLove閱讀 2,608評論 0 4
  • 跟原生開發相比,H5的開發相對來一個成熟的框架和團隊來講在開發速度和開發效率上有著比原生很大的優勢,至少不用等待審...
    大沖哥閱讀 1,866評論 0 7