Caps-iOS/Caps/Camera/ContentViewModel.swift

58 lines
1.3 KiB
Swift
Raw Normal View History

2022-06-10 21:20:49 +02:00
import CoreImage
import AVFoundation
import UIKit
class ContentViewModel: ObservableObject {
@Published var error: Error?
@Published var frame: CGImage?
@Published var image: UIImage?
private let context = CIContext()
private let cameraManager = CameraManager.shared
private let frameManager = FrameManager.shared
init() {
setupSubscriptions()
}
func setupSubscriptions() {
frameManager.image = nil
frameManager.current = nil
cameraManager.$error
.receive(on: RunLoop.main)
.map { $0 }
.assign(to: &$error)
frameManager.$current
.receive(on: RunLoop.main)
.compactMap { buffer in
guard let image = CGImage.create(from: buffer) else {
return nil
}
let ciImage = CIImage(cgImage: image)
return self.context.createCGImage(ciImage, from: ciImage.extent)
}
.assign(to: &$frame)
frameManager.$image
.receive(on: RunLoop.main)
.assign(to: &$image)
}
func endCapture() {
cameraManager.stopVideoCaptureSession()
}
func startCapture() {
cameraManager.startVideoCapture()
}
func captureImage() {
cameraManager.capturePhoto(delegate: frameManager)
}
}