直接上代码:
首先遵守代理
<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