I would like use camera in my iPhone inside of View. I don\'t want use typical full screen camera view, but my own.
For example I would like have a square 200x200 at the
An another code block. how you can do manual focus with iPhone.
import UIKit
class ViewController: UIViewController {
@IBOutlet var cameraView: CameraView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sliderChanged(sender: UISlider) {
cameraView.setFocusWithLensPosition(sender.value)
}
}
import UIKit
import AVFoundation
class CameraView: UIView {
// AVFoundation properties
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice!
var captureDeviceFormat: AVCaptureDeviceFormat?
let stillImageOutput = AVCaptureStillImageOutput()
var cameraLayer: AVCaptureVideoPreviewLayer?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initCamera()
}
func initCamera() {
captureSession.beginConfiguration()
stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
// get the back camera
if let device = cameraDeviceForPosition(AVCaptureDevicePosition.Back) {
captureDevice = device
captureDeviceFormat = device.activeFormat
let error: NSErrorPointer = nil
do {
try captureDevice!.lockForConfiguration()
} catch let error1 as NSError {
error.memory = error1
}
captureDevice!.focusMode = AVCaptureFocusMode.Locked
captureDevice!.unlockForConfiguration()
var deviceInput: AVCaptureDeviceInput!
do {
deviceInput = try AVCaptureDeviceInput(device: captureDevice)
} catch let error1 as NSError {
error.memory = error1
deviceInput = nil
}
if(error == nil) {
captureSession.addInput(deviceInput)
}
captureSession.addOutput(stillImageOutput)
// use the high resolution photo preset
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
// setup camera preview
cameraLayer = AVCaptureVideoPreviewLayer(session: captureSession)
if let player = cameraLayer {
player.videoGravity = AVLayerVideoGravityResizeAspectFill
self.layer.addSublayer(player)
player.frame = self.layer.bounds
player.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
}
// commit and start capturing
captureSession.commitConfiguration()
captureSession.startRunning()
}
captureSession.commitConfiguration()
}
func setFocusWithLensPosition(pos: CFloat) {
let error: NSErrorPointer = nil
do {
try captureDevice!.lockForConfiguration()
} catch let error1 as NSError {
error.memory = error1
}
captureDevice!.setFocusModeLockedWithLensPosition(pos, completionHandler: nil)
captureDevice!.unlockForConfiguration()
}
// return the camera device for a position
func cameraDeviceForPosition(position:AVCaptureDevicePosition) -> AVCaptureDevice?
{
for device:AnyObject in AVCaptureDevice.devices() {
if (device.position == position) {
return device as? AVCaptureDevice;
}
}
return nil
}
}