A package for interacting with the cameras in iOS. Developed by Sam Stone.
A package for interacting with the cameras in iOS, with the following features:
- Displaying the camera preview.
- Taking a picture.
- Setting the camera to take the picture from.
The other aim of this project is to provide a well tested solution to this project, which bases itself on Clean Architecture, pushing technology concerns to the boundaries and testing everything in-between.
The API can be found in the Camera
interface.
Go to File > Swift Packages > Add Package Dependency and add the following URL:
https://github.com/samst-one/CameraCapture
- First we need to import the camera into our project, we do this by importing the framework
import Camera
- Next we need to create a
Camera
object. TheCamera
acts as the API for the package. To create theCamera
, we do:
let camera = CameraFactory.make()
- With the
camera
, we can now access the API. For more of a breakdown of the API, please check outCamera
. To get a list of available devices we can use to take a picture, call:
camera.availableDevices
- Pick a camera from the selection above, and set the camera using the
id
from theDevice
returned.CameraSourcingError.invalidCamera
will be thrown if camera cannot be found on the current device.
do {
try camera.set(camera!.id)
} catch let error {
print(error)
}
- Set the preview view where you want to display it. Can also be wrapped in a
UIViewRepresentable
.
let previewView = camera.previewView
view.addSubview(previewView)
- Next we can start the camera. The callback is called when the camera has finished its start up process. This will show the preview in the
previewView
.
camera.start {
// Do stuff here
}
- When you're ready to take a photo, call
takePhoto
on theCamera
. If successful, aData
representation of the image will be returned. If an error has occurred, then aPhotoCaptureError
will be returned.
camera.takePhoto(with: CameraSettings(fileType: .jpeg)) { result in
switch result {
case .success(let data):
let image = UIImage(data: data)
break
case .failure(let error):
break
}
}
In conclusion, to start up the camera and take a picture, the full code is below:
let camera = CameraFactory.make()
let selectedDevice = camera.availableDevices.randomElement()
let view = camera.previewView
do {
try camera.set(camera!.id)
} catch let error {
print(error)
}
view.addSubview(view)
camera.start {
camera.takePhoto(with: CameraSettings(fileType: .jpeg)) { result in
switch result {
case .success(let data):
let image = UIImage(data: data)
break
case .failure(let error):
break
}
}
}