iOS UIWebView 中 js调用OC 打开相册 获取图片, OC调用js 将图片加载到html上

时间:2021-12-25 07:19:46

线上html

<!DOCTYPE html>
<html>
<head>
<title>HTML中用JS调用OC方法</title>
<style> #div1 {
background-color:#ccc;
width:100px;
height:100px;
position:absolute;
top:400px
} </style> <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
<script> function getImg(url) { var oDiv = document.getElementById("div1");
var oImg = document.getElementById("img1"); oImg.src = url; } </script>
</head>
<body> <p id="div1">
<img id="img1" src="" height="200" width="200" />
</p> <br/> <a href='ios://openMyAlbum'>打开相册</a><br><br/> </body> </html>

在oc中

//
// ViewController.m
//
// Created by Hwangkop on 15/11/30.
// Copyright © 2015年 Hp. All rights reserved.
// #import "ViewController.h"
#import <AVFoundation/AVFoundation.h> @interface ViewController () <UIWebViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{ UIWebView *_webView;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_webView]; NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index"
ofType:@"html"];
NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
encoding:NSUTF8StringEncoding
error:nil];
[_webView loadHTMLString:htmlCont baseURL:baseURL]; _webView.delegate = self; } -(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { //通过url获取 js方法在oc中实现该方法
NSString *urlstr = request.URL.absoluteString; NSRange range = [urlstr rangeOfString:@"ios://"]; if (range.length!=0) { NSString *method = [urlstr substringFromIndex:(range.location+range.length)]; SEL selctor = NSSelectorFromString(method); [self performSelector:selctor withObject:nil];
} return YES; } //要实现的方法
-(void)openMyAlbum { UIImagePickerController *vc = [[UIImagePickerController alloc] init];
vc.delegate = self;
vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:vc animated:YES completion:nil]; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info { UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_100.png"]]; // 保存
[UIImagePNGRepresentation(image)writeToFile: filePath atomically:YES]; [picker dismissViewControllerAnimated:YES completion:^{ // NSLog(@"%@", filePath);
// oc 调用js 并且传递图片路径参数
[_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getImg('%@')", filePath]];
}];
} @end