0

我的要求是编写一个示例 IOS 应用程序,它会自动捕获相机图片。使用提供的各种 SO 链接,我确实实现了以下代码 -

我的 CameraViewController.h 类定义如下:

@interface CameraViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) IBOutlet UIImageView *ImageView;

@end

CameraViewController.m 有以下代码:

    -(void)viewDidAppear:(BOOL)animated
{
    NSLog(@"Setting the background now");

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    picker.showsCameraControls = NO;
    picker.navigationBarHidden = NO;
    picker.toolbarHidden = NO;
    [self presentViewController:picker animated:YES completion:NULL];

    NSLog(@"Taking the picture now");
   [picker takePicture];


}


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

{
    NSLog(@"Entered the case of finishing pictures");
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker
{
    NSLog(@"Entered the case of cancel");

}

以上代码的作用是成功启动相机应用程序,但是我不确定 takePicture API 是否能够成功单击图片。我在我的 Ipad 内的照片应用程序中没有看到任何保存的图片,所以我认为该图片没有被点击。有人可以告诉我上面的代码是否正确,或者一旦显示相机控件,我需要做什么来自动执行单击捕获按钮的部分

4

4 回答 4

2

[请转到 Apple 文档中的“使用 UIImagePickerController 选择图片并拍照”,了解cameraOverlayView类的属性,UIImagePickerController以获取满足您需要的完整示例应用程序,等等。]

您指定您CameraViewController采用该UIImagePickerControllerDelegate协议,因此您必须实现两条消息:

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

- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker;

正如 iOS 文档所描述的,NSDictionary* info有一个UIImagePickerControllerOriginalImage将返回UIImage. 像这样访问它:

UIImage *snapshot = (UIImage *) [info objectForKey: UIImagePickerControllerOriginalImage];

由于您的计划是自动拍照(无需用户交互),takePicture因此请务必指定

  picker.showsCameraControls = NO;
于 2013-10-21T22:04:43.290 回答
1

你需要实现 UIImagePIckerControllerDelegate 的 imagePickerController:didFinishPickingMediaWithInfo: 方法。

之后,查看 mediaInfo 字典,里面有一个 UIImage 可以使用。

于 2013-10-21T21:48:36.643 回答
0

我知道这很旧,但是使用计时器的更好替代方法(请参阅已接受答案中的评论)是实现完成处理程序而不是传入 NULL。

[self presentViewController:picker animated:YES completion:^{
    NSLog(@"Taking the picture now");
    [picker takePicture];
}];

这样,每次都能始终如一地拍摄照片,并且您不会浪费时间添加不必要的延迟。

于 2015-02-04T22:24:32.287 回答
0
**You can auto capturing both camera image and video recording by use this code.**

import UIKit
import AVFoundation
import MobileCoreServices

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    let captureSession = AVCaptureSession()
    var captureDevice : AVCaptureDevice?
    var imagePicker = UIImagePickerController()
    var flagVideoRecording = false
    var arrImages = [UIImage]()
    var countVideoRecording = 0
    var labelTime = UILabel()
    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(actionRepeatCapturing), name: .AVCaptureSessionDidStartRunning, object: nil)
    }
    
    @objc func actionRepeatCapturing() {
        flagVideoRecording = false
        startCapturingBothImageAndRecordView()
    }
    
    //MARK:- UIButton's Action
    @IBAction func actionCaptureImage(_ sender: UIButton) {
        flagVideoRecording = false
        
        if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) ==  AVAuthorizationStatus.authorized {
            startCapturingBothImageAndRecordView()
        } else {
            AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in
                if granted == true {
                    self.startCapturingBothImageAndRecordView()
                } else {
                    DispatchQueue.main.async {
                        self.alertToEncourageAccessInitially("Camera access required for capturing photos!", actionTitle: "Allow Camera")
                    }
                }
            })
        }
    }
    
    @IBAction func actionCaptureVideo(_ sender: UIButton) {
        flagVideoRecording = true
        if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) ==  AVAuthorizationStatus.authorized {
            switch AVAudioSession.sharedInstance().recordPermission {
            case AVAudioSession.RecordPermission.granted:
                self.startCapturingBothImageAndRecordView()
            case AVAudioSession.RecordPermission.denied:
                self.alertToEncourageAccessInitially("Microphone access required for record your voice!", actionTitle: "Allow Microphone")
            case AVAudioSession.RecordPermission.undetermined:
                
                AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
                    if granted {
                        self.startCapturingBothImageAndRecordView()
                    } else {
                        self.alertToEncourageAccessInitially("Microphone access required for record your voice!", actionTitle: "Allow Microphone")
                    }
                })
                
            default:
                break
            }
        } else {
            AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in
                if granted == true {
                    switch AVAudioSession.sharedInstance().recordPermission {
                    case AVAudioSession.RecordPermission.granted:
                        self.startCapturingBothImageAndRecordView()
                    case AVAudioSession.RecordPermission.denied:
                        self.alertToEncourageAccessInitially("Microphone access required for record your voice!", actionTitle: "Allow Microphone")
                    case AVAudioSession.RecordPermission.undetermined:
                        
                        AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
                            if granted {
                                self.startCapturingBothImageAndRecordView()
                            } else {
                                self.alertToEncourageAccessInitially("Microphone access required for record your voice!", actionTitle: "Allow Microphone")
                            }
                        })
                        
                    default:
                        break
                    }
                } else {
                    DispatchQueue.main.async {
                        self.alertToEncourageAccessInitially("Camera access required for record video", actionTitle: "Allow Camera")
                    }
                }
            })
        }
    }
}

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func startCapturingBothImageAndRecordView() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
            debugPrint("captureVideoPressed and camera available.")
            imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            if flagVideoRecording {
                imagePicker.mediaTypes = [kUTTypeMovie as String]
                imagePicker.allowsEditing = false
                imagePicker.showsCameraControls = false
                
                let viewTime = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40))
                viewTime.backgroundColor = .black
                viewTime.alpha = 0.1
                labelTime = UILabel(frame: CGRect(x: self.view.frame.width/2-50, y: 10, width: 100, height: 25))
                labelTime.font = UIFont.boldSystemFont(ofSize: 17)
                labelTime.text = "00.00:00"
                labelTime.textColor = .white
                labelTime.textAlignment = .center
                labelTime.backgroundColor = .red
                imagePicker.view.addSubview(viewTime)
                imagePicker.view.addSubview(labelTime)
                
                self.timer = Timer.scheduledTimer(timeInterval: 1,
                                     target: self,
                                     selector: #selector(self.actionStopVideoRecording),
                                     userInfo: nil,
                                     repeats: true)
            } else {
                imagePicker.allowsEditing = false
                imagePicker.showsCameraControls = false
            }
        } else {
            debugPrint("Camera not available.")
        }
        
        
        self.present(self.imagePicker, animated: true, completion: {
            if self.flagVideoRecording {
                self.imagePicker.startVideoCapture()
            } else {
                self.imagePicker.takePicture()
            }
        })
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if flagVideoRecording {
            if let videoFileURL = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
                debugPrint(videoFileURL)
                
//                let data = try Data(contentsOf: videoFileURL, options: .mappedIfSafe)
//                debugPrint(data)
            }
            self.dismiss(animated: true, completion: nil)
        } else {
            if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
                arrImages.append(pickedImage)
            }
            
            sleep(1)
            
            if arrImages.count >= 5 {
                self.dismiss(animated: true, completion: nil)
            } else {
                NotificationCenter.default.post(name: .AVCaptureSessionDidStartRunning, object: nil, userInfo: nil)
            }
        }
    }
    
    @objc func actionStopVideoRecording() {
        countVideoRecording += 1
        labelTime.text = countVideoRecording == 10 ? "00:00:\(countVideoRecording)":"00:00:0\(countVideoRecording)"
        
        if countVideoRecording == 10 {
            imagePicker.stopVideoCapture()
            timer?.invalidate()
            timer = nil
        }
    }
}

extension ViewController {
    func alertToEncourageAccessInitially(_ msgString: String, actionTitle: String) {
        let alert = UIAlertController(
            title: "IMPORTANT",
            message: msgString,
            preferredStyle: UIAlertController.Style.alert
        )
        alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: actionTitle, style: .destructive, handler: { (alert) -> Void in
            let myUrl = URL(string: UIApplication.openSettingsURLString)!
                if let url = URL(string: "\(myUrl)"), !url.absoluteString.isEmpty {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }

                // or outside scope use this
                guard let url = URL(string: "\(myUrl)"), !url.absoluteString.isEmpty else {
                   return
                }
                 UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }))
        present(alert, animated: true, completion: nil)
    }
}
于 2021-08-17T12:06:26.950 回答