JustScanIt/JustScanIt/View/MainView.swift
2024-07-03 18:32:13 +12:00

88 lines
2.4 KiB
Swift

//
// MainView.swift
// JustScanIt
//
// Created by Pradyun Setti on 03/07/2024.
//
import SwiftUI
import SwiftData
import AVKit
struct MainView: View {
@Environment(\.modelContext) var ctx
@State private var scannedImages: [UIImage] = []
@State private var isShowingVNDocumentCameraView = false
@Query var scans: [Scan]
var isAuthorized: Bool {
get async {
let status = AVCaptureDevice.authorizationStatus(for: .video)
// Determine if the user previously authorized camera access.
var isAuthorized = status == .authorized
// If the system hasn't determined the user's authorization status,
// explicitly prompt them for approval.
if status == .notDetermined {
isAuthorized = await AVCaptureDevice.requestAccess(for: .video)
} else if status == .denied {
// TODO: show alert when denied
}
return isAuthorized
}
}
var body: some View {
NavigationView {
ScrollView {
ForEach(scans, id: \.self) { scan in
HStack {
ForEach(scan.uiImages, id: \.self) { image in
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(width: 100, height: 100)
.padding()
}
}
}
}
.navigationTitle("Just Scan It!")
.sheet(isPresented: $isShowingVNDocumentCameraView, onDismiss: saveImages) {
VNDocumentCameraViewControllerRepresentable(scanResult: $scannedImages)
}
.toolbar {
ToolbarItem {
Button(action: showVNDocumentCameraView) {
Image(systemName: "scanner")
}
}
}
}
}
private func showVNDocumentCameraView() {
Task { guard await isAuthorized else { return } }
isShowingVNDocumentCameraView = true
}
private func saveImages() {
let newScan = Scan(images: scannedImages)
ctx.insert(newScan)
try? ctx.save()
scannedImages = []
}
}
#Preview {
MainView()
}