Skip to content

samst-one/CameraCapture

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Camera

A badge showing the current build status on bitrise. Please click to view more A badge showing the Swift Compatibility of the project. A badge showing the platform compatibility of the project.

Overview

A package that hopes to provide a simplified API 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.
  • Setting the flash state.

The API can be found in the Camera interface.

Install

Go to File > Swift Packages > Add Package Dependency and add the following URL:

https://github.com/samst-one/CameraCapture

Usage

  1. First we need to import the camera into our project, we do this by importing the framework
import CameraCapture
  1. Next we need to create a Camera object. The Camera acts as the API for the package. To create the Camera, we do:
let camera = CameraFactory.make()
  1. With the camera, we can now access the API. For more of a breakdown of the API, please check out Camera. To get a list of available devices we can use to take a picture, call:
camera.availableDevices
  1. Pick a camera from the selection above, and set the camera using the id from the Device 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)
}
  1. Set the preview view where you want to display it. Can also be wrapped in a UIViewRepresentable.
let previewView = camera.previewView
view.addSubview(previewView)
  1. 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
}
  1. When you're ready to take a photo, call takePhoto on the Camera. If successful, a Data representation of the image will be returned. If an error has occurred, then a PhotoCaptureError 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
    }
}

Summary

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
        }
    }
}