首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将UIViewRepresentable连接到SwiftUI

将UIViewRepresentable连接到SwiftUI
EN

Stack Overflow用户
提问于 2021-12-15 18:30:01
回答 1查看 476关注 0票数 1

我有一个基于SwiftUI的应用程序,它有一个简单的按钮,当按下这个按钮时,应该从AVFoundation打开一个相机类,它也使用UIKit。在那张纸下面,我不知道到底该放什么地方。我尝试了CameraSession()和其他一些想法,但我有点迷失在连接这个SwiftUI按钮来打开相机应用程序上。谢谢!

//内容视图

代码语言:javascript
复制
import SwiftUI

struct ContentView: View {
    //@State private var image: Image?
    @State private var showingCameraSession = false
    //@Binding var isShown: Bool
    var body: some View {
        VStack{
            
            ControlButton(systemIconName: "slider.horizontal.3"){
            //Button("Seelect Image") {
                showingCameraSession = true
            } .sheet(isPresented: $showingCameraSession){
            //What to place here?

                
            }
           
       }
    }
}

//CameraSession

代码语言:javascript
复制
import AVFoundation
//import RealityKit
import UIKit
import SwiftUI



struct CameraSession : UIViewControllerRepresentable {
    //@Binding var isShown: Bool
    typealias UIViewControllerType = CaptureSession
    
    func makeUIViewController(context: Context) -> CaptureSession{
        return CaptureSession()
    }

    func updateUIViewController(_ uiViewController: CaptureSession, context: Context) {
           // if(self.isShown){
                //CameraSession.didTapTakePhoto()
               // shutterButton.addTarget(self, action: #selector(didTapTakePhoto), for: .touchUpInside) //tie button to actual function
            }
        }





class CaptureSession: UIViewController {
    //@Binding var isShown: Bool
    
    
     //Reference: https://www.youtube.com/watch?v=ZYPNXLABf3c
    //CaptureSession
    var session: AVCaptureSession?
    //PhotoOutput  --> to the Cloud
    let output = AVCapturePhotoOutput()
    // Video Preview
    let previewLayer = AVCaptureVideoPreviewLayer()
    
    
    //Shutter Button
    
    private let shutterButton: UIButton = {
        let button = UIButton(frame: CGRect(x:0, y:0, width: 100, height: 100))
        button.layer.cornerRadius = 50
        button.layer.borderWidth = 10
        button.layer.borderColor = UIColor.white.cgColor
        return button
        
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        //previewLayer.backgroundColor = UIColor.systemRed.cgColor
        view.layer.addSublayer(previewLayer)
        view.addSubview(shutterButton)
        checkCameraPermissions()
      
       shutterButton.addTarget(self, action: #selector(didTapTakePhoto), for: .touchUpInside) //tie button to actual function
    }
    
    override func viewDidLayoutSubviews(){
        super.viewDidLayoutSubviews()
        previewLayer.frame = view.bounds
        
        shutterButton.center = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height - 100)
    }
    
    private func checkCameraPermissions() {
        switch AVCaptureDevice.authorizationStatus(for: .video){
            
        case .notDetermined:
            //Request Permission
            AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
                guard granted else {
                    return
                }
                DispatchQueue.main.async{
                    self?.setUpCamera()
                }
            }
        case .restricted:
            break
        case .denied:
            break
        case .authorized:
            setUpCamera()
        @unknown default:
            break
        }
    }
    //with Photogrammetry, you also have to create a session similar https://developer.apple.com/documentation/realitykit/creating_3d_objects_from_photographs/
    // example app: https://developer.apple.com/documentation/realitykit/taking_pictures_for_3d_object_capture
    private func setUpCamera(){
        let session = AVCaptureSession()
        if let device = AVCaptureDevice.default(for: .video){
            do{
                let input = try AVCaptureDeviceInput(device: device)
                if session.canAddInput(input){
                    session.addInput(input) //some Devices contract each other.
                }
                if session.canAddOutput(output) {
                    session.addOutput(output)
                }
                previewLayer.videoGravity = .resizeAspectFill //content does not get distored or filled
                previewLayer.session = session
                 
                
                session.startRunning()
                self.session = session
                
            }
            catch{
                print(error)
            }
        }
    }
    //originally private
    @objc private func didTapTakePhoto() {
       
         output.capturePhoto(with: AVCapturePhotoSettings(),
                            delegate: self)
       // let vc = UIHostingController(rootView: ContentView())
       // present(vc, animated: true)
        
    }
}
 //AVCaptureOutput is AVFoundations version of photo output
extension CaptureSession: AVCapturePhotoCaptureDelegate {
    func photoOutput( output: AVCaptureOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error:
                      Error?){
                      guard let data = photo.fileDataRepresentation() else { //where to store file information
                        return
                      }
                    let image = UIImage(data: data)
        
        session?.stopRunning()
        
        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFill
        imageView.frame = view.bounds
        view.addSubview(imageView)
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-16 08:07:29

因此,首先,让您的应用程序拥有访问用户相机的权限(转到顶部构建设置旁边的Info.plist或info选项卡,添加隐私相机用法,并添加“我们需要您的相机执行此操作”)。

在那之后,表的修饰符中的一个简单调用就可以了。

代码语言:javascript
复制
struct ContentView: View {
    //@State private var image: Image?
    @State private var showingCameraSession = false
    //@Binding var isShown: Bool
    var body: some View {
        VStack{
            
//            ControlButton(systemIconName: "slider.horizontal.3"){
            Button("Seelect Image") {
                showingCameraSession = true
            } .sheet(isPresented: $showingCameraSession){
            //What to place here?
                
                CameraSession()

                
            }
           
       }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70368653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档