iOS 中 UIWebView控件实现js与Objective-C交互 (获取摄像头和相册)

UIWebView是iOS开发中常用的一个视图控件,多数情况下,它被用来显示HTML格式的内容。

iOS 6以上版本的Mobile Safari支持在网页中调用摄像头,只需要放置以下代码:

但是iOS 5的浏览器还不支持这个功能,如果需要调用摄像头,则依然需要通过Hybrid开发方式来实现。

代码如下:


iOS 中 UIWebView控件实现js与Objective-C交互 (获取摄像头和相册)_第1张图片
iOS 中 UIWebView控件实现js与Objective-C交互 (获取摄像头和相册)_第2张图片


iOS 中 UIWebView控件实现js与Objective-C交互 (获取摄像头和相册)_第3张图片


iOS 中 UIWebView控件实现js与Objective-C交互 (获取摄像头和相册)_第4张图片

#import "ViewController.h"

#import "NSData+Base64.h"

@interface UIWebViewCallCameraViewController ()

{

NSString *callback;    // 定义变量用于保存返回函数

}

@end

@implementation UIWebViewCallCameraViewController

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

// 设置delegate并载入html文件

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];

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{

NSString *requestString = [[request URL] absoluteString];

NSString *protocol = @"js-call://"; //协议名称

if ([requestString hasPrefix:protocol]) {

NSString *requestContent = [requestString substringFromIndex:[protocol length]];

NSArray *vals = [requestContent componentsSeparatedByString:@"/"];

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 presentModalViewController:imagePicker animated:YES];

}

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])

{

// 返回图片

UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];

// 设置并显示加载动画

UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"正在处理图片..." message:@"\n\n"

delegate:self

cancelButtonTitle:nil

otherButtonTitles:nil, nil];

UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc]

initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

loading.center = CGPointMake(139.5, 75.5);

[av addSubview:loading];

[loading startAnimating];

[av show];

// 在后台线程处理图片

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

// 这里可以对图片做一些处理,如调整大小等,否则图片过大显示在网页上时会造成内存警告

// 图片转换成base64字符串

NSString *base64 = [UIImagePNGRepresentation(originalImage) base64Encoding];

[self performSelectorOnMainThread:@selector(doCallback:) withObject:base64 waitUntilDone:NO];  // 把结果显示在网页上

[av dismissWithClickedButtonIndex:0 animated:YES];

});

}

[picker dismissModalViewControllerAnimated:YES];

}

- (void)doCallback:(NSString *)data

{

[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@('%@');", callback, data]];

}

@end

你可能感兴趣的:(iOS 中 UIWebView控件实现js与Objective-C交互 (获取摄像头和相册))