UIWebView是iOS開(kāi)發(fā)中常用的一個(gè)視圖控件,多數(shù)情況下喂江,它被用來(lái)顯示HTML格式的內(nèi)容琅翻。
iOS 6以上版本的Mobile Safari支持在網(wǎng)頁(yè)中調(diào)用攝像頭,只需要放置以下代碼:
<input type = "file" capture = "camera" accept = "image/*" id = "cameraInput">
但是iOS 5的瀏覽器還不支持這個(gè)功能窃躲,如果需要調(diào)用攝像頭计贰,則依然需要通過(guò)Hybrid開(kāi)發(fā)方式來(lái)實(shí)現(xiàn)钦睡。
代碼如下:
#import "ViewController.h"
#import "NSData+Base64.h"
@interface UIWebViewCallCameraViewController ()
{
NSString *callback;? ? // 定義變量用于保存返回函數(shù)
}
@end
@implementation UIWebViewCallCameraViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 設(shè)置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://"; //協(xié)議名稱
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"])? ? ? // 圖庫(kù)
{
callback = [vals objectAtIndex:1];
[self doAction:UIImagePickerControllerSourceTypePhotoLibrary];
}
else if([[vals objectAtIndex:0] isEqualToString:@"album"])? ? ? // 相冊(cè)
{
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:@"沒(méi)有可用的照片來(lái)源" 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];
// 設(shè)置并顯示加載動(dòng)畫
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];
// 在后臺(tái)線程處理圖片
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// 這里可以對(duì)圖片做一些處理,如調(diào)整大小等躁倒,否則圖片過(guò)大顯示在網(wǎng)頁(yè)上時(shí)會(huì)造成內(nèi)存警告
// 圖片轉(zhuǎn)換成base64字符串
NSString *base64 = [UIImagePNGRepresentation(originalImage) base64Encoding];
[self performSelectorOnMainThread:@selector(doCallback:) withObject:base64 waitUntilDone:NO];? // 把結(jié)果顯示在網(wǎng)頁(yè)上
[av dismissWithClickedButtonIndex:0 animated:YES];
});
}
[picker dismissModalViewControllerAnimated:YES];
}
- (void)doCallback:(NSString *)data
{
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@('%@');", callback, data]];
}
@end