i'm working on this assignment where we have to build a custom camera feature and store images into the phone gallery. So i kinda did almost until the camera preview but i'm not sure yet how to capture and store the images using swift 3.
Here's the source code :
var captureSession = AVCaptureSession()
var sessionOutput = AVCapturePhotoOutput()
var previewLayer = AVCaptureVideoPreviewLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
let deviceSession = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDuoCamera,.builtInTelephotoCamera], mediaType: AVMediaTypeVideo, position: .unspecified)
for device in (deviceSession?.devices)! {
if device.position == AVCaptureDevicePosition.back {
do {
let input = try AVCaptureDeviceInput.init(device: device)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
if captureSession.canAddOutput(sessionOutput) {
captureSession.addOutput(sessionOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.connection.videoOrientation = .portrait
cameraLayerView.layer.addSublayer(previewLayer)
cameraLayerView.addSubview(topControllerView)
cameraLayerView.addSubview(bottomControllerView)
previewLayer.position = CGPoint(x: self.cameraLayerView.frame.width / 2, y: self.cameraLayerView.frame.height / 2)
previewLayer.bounds = cameraLayerView.frame
captureSession.startRunning()
}
}
} catch let avError {
print(avError)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
@IBAction func galleryAction(_ sender: UIButton) {
// This part shows the thumbnail of a current image been taken
}
@IBAction func captureAction(_ sender: UIButton) {
// This is the part i have capture the image
}
Taking the picture it's really simple, take a look here. To present the image picker:
Getting the taken/selected image:
Now, saving the UIImage to the photo album can be done like explained here. The following call will save the photo to the gallery and call a completion handler:
The handler is something like: