在打開相機拍照或者打開相冊選擇圖片以前, 有必要先判斷先是否有權限, 若是沒有權限應該給個提示, 讓用戶本身去設置權限.ide
判斷是否有相機權限:測試
//首先須要導入頭文件: #import <AVFoundation/AVFoundation.h> // 判斷是夠有全向訪問相機 AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) { //無權限 NSLog(@"沒有訪問相機權限"); return; }
判斷是否有相冊權限:code
網上找了不少, 都是說用另外一個類來判斷的, 叫什麼名字忘了, 可是是不能用的, 正確姿式是使用PHPhotoLibrary
這個類.圖片
//首先須要導入頭文件: #import <Photos/PHPhotoLibrary.h> // 判斷是否有訪問相冊的權限 PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus]; if (author == PHAuthorizationStatusRestricted || author ==PHAuthorizationStatusDenied){ //無權限 NSLog(@"沒有訪問相冊的權限"); return; }
從相機或者相冊選擇照片須要用到UIImagePickerController
類.ip
從相機選擇照片:get
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; imagePicker.allowsEditing = YES; imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentViewController:imagePicker animated:YES completion:nil];
從相冊選擇照片:it
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; imagePicker.allowsEditing = YES; imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:imagePicker animated:YES completion:nil];
拍照方式選擇照片時候, 通常須要將照片保存到本地相冊中, 保存相冊的代碼只有一個方法, 以下所示.io
// 將拍照的圖片保存到本地 UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
須要注意的是, 第一個參數是要保存的圖片, 第二個參數是要執行方法的target, 第三個參數是selector, 第四個參數是傳參數. 第三個參數selector, selector的方法名字通常是有參數的(測試寫無參數的, 保存時候回崩潰).import
//此方法通常是三個參數, 不然容易出錯. - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { NSString *message = @"呵呵"; if (!error) { message = @"成功保存到相冊"; }else { message = [error description]; } NSLog(@"message is %@",message); }