美文网首页ios实用开发技巧OC进化iOS学习笔记
iOS在UIWebView中通过Javascript调用摄像头、

iOS在UIWebView中通过Javascript调用摄像头、

作者: 我是七月 | 来源:发表于2017-06-15 23:15 被阅读119次
    奋斗的七月

    直接上代码:

    首先遵守代理

    <HTSelectPhotoDelegate,UIActionSheetDelegate,UITextViewDelegate,UIWebViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
    {
        NSString *callback;
    }
    
    
    - (void)viewDidLoad{
        
        [super viewDidLoad];
        
        self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.view addSubview:self.webView];
        self.webView.delegate = self;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"camera" ofType:@"html"];
        NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [self.webView loadHTMLString:fileContent baseURL:nil];
    }
    
    
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        
        DDLog(@"URL==%@",[request URL]);
        
        NSString *requestString = [[request URL] absoluteString];
        NSString *protocol = @"js-call://";
        
        if ([requestString hasPrefix:protocol]) {
            
            NSString *requestContent = [requestString substringFromIndex:[protocol length]];
            NSArray *vals = [requestContent componentsSeparatedByString:@"/"];
            DDLog(@"vals==%@",vals);
            if ([[vals objectAtIndex:0] isEqualToString:@"camera"]) {
                callback = [vals objectAtIndex:1];
                [self doAction:UIImagePickerControllerSourceTypeCamera];
            } else if([[vals objectAtIndex:0] isEqualToString:@"photolibrary"]) {
                callback = [vals objectAtIndex:1];
                [self doAction:UIImagePickerControllerSourceTypePhotoLibrary];
            } else if([[vals objectAtIndex:0] isEqualToString:@"album"]) {
                callback = [vals objectAtIndex:1];
                [self doAction:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            }else{
                [webView stringByEvaluatingJavaScriptFromString:@"alert('未定义/lwme.cnblogs.com');"];
            }
            return NO;
        }
        return YES;
    }
    
    - (void)doAction:(UIImagePickerControllerSourceType)sourceType
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
            imagePicker.sourceType = sourceType;
        } else {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"照片获取失败" message:@"没有可用的照片来源" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [av show];
            return;
        }
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
            [popover presentPopoverFromRect:CGRectMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 3, 10, 10) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        } else {
            [self presentViewController:imagePicker animated:YES completion:nil];
    //        [self presentModalViewController:imagePicker animated:YES];
        }
    }
    
    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
    {
        if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]){
            
            UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"正在处理图片..." message:nil
                                                        delegate:self
                                               cancelButtonTitle:nil
                                               otherButtonTitles:nil, nil];
            [alertView show];
    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
                
    //            NSString *base64 = [UIImagePNGRepresentation(originalImage) base64Encoding];
                NSData *dataIMG = UIImageJPEGRepresentation(originalImage, 0.4);
                NSString *base64=[dataIMG base64EncodedStringWithOptions:NSUTF8StringEncoding];
    
                [self performSelectorOnMainThread:@selector(doCallback:) withObject:base64 waitUntilDone:NO];
                [alertView dismissWithClickedButtonIndex:0 animated:YES];
                
            });
        }
        
        [picker dismissViewControllerAnimated:YES completion:nil];
    //    [picker dismissModalViewControllerAnimated:YES];
    }
    
    - (void)doCallback:(NSString *)data
    {
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@('%@');", callback, data]];
    }
    
    

    附上camera.html源码如下:

    <script>
        function cameraCallback(imageData) {
            var img = createImageWithBase64(imageData);
            document.getElementById("cameraWrapper").appendChild(img);
        }
        function photolibraryCallback(imageData) {
            var img = createImageWithBase64(imageData);
            document.getElementById("photolibraryWrapper").appendChild(img);
        }
        function albumCallback(imageData) {
            var img = createImageWithBase64(imageData);
            document.getElementById("albumWrapper").appendChild(img);
        }
        function createImageWithBase64(imageData) {
            var img = new Image();
            img.src = "data:image/jpeg;base64," + imageData;
            img.style.width = "50px";
            img.style.height = "50px";
            return img;
        }
    </script>
    <p style="text-align:center;padding:20px;">
        <a href="js-call://camera/cameraCallback">拍照</a>  
        <a href="js-call://photolibrary/photolibraryCallback">图库</a>  
        <a href="js-call://album/albumCallback">相册</a>
    </p>
    
    <fieldset>
        <legend>拍照</legend>
        <div id="cameraWrapper">
        </div>
    </fieldset>
    
    <fieldset>
        <legend>图库</legend>
        <div id="photolibraryWrapper">
        </div>
    </fieldset>
    
    <fieldset>
        <legend>相册</legend>
        <div id="albumWrapper">
        </div>
    </fieldset>
    

    详细示例,在github可以下载
    https://github.com/corminlu/UIWebViewCallCamera

    相关文章

      网友评论

      • Z了个Y:可以考虑使用webviewjavascriptbrige 这个框架,代码更精简
        我是七月:@Z了个Y 恩 好的, 我看下这个,谢了
        Z了个Y:不需要
        我是七月:@Z了个Y iOS用webviewjavascriptbrige的话,是不是需要后台也要用这个相应的框架?

      本文标题:iOS在UIWebView中通过Javascript调用摄像头、

      本文链接:https://www.haomeiwen.com/subject/kppdqxtx.html