【问题标题】:How to implement camera functionality in iOS app through XCode如何通过 XCode 在 iOS 应用中实现相机功能
【发布时间】:2020-06-30 22:02:58
【问题描述】:

我从零开始开发 iOS 应用程序,但我需要创建一个可以使用 iPhone 相机拍摄图像的应用程序。我找到了 UIImagePickerController 但我无法弄清楚如何正确实现它。如果有人可以帮助我,那就太好了。此外,我对应用程序开发知之甚少,因此如果有任何背景知识,我将不胜感激。

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    你可以在任何你想打开 UIImagePickerController 的地方调用这个方法:

    func openImagePicker() {
        let vc = UIImagePickerController()
        vc.sourceType = .camera
        vc.allowsEditing = true
        vc.delegate = self
        present(vc, animated: true)
    }
    

    通过制作这样的扩展,使您的视图控制器同时符合 UINavigationControllerDelegate 和 UIImagePickerControllerDelegate:

    extension youViewControllerClass: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            
            picker.dismiss(animated: true) // dismisses camera controller
    
            guard let image = info[.editedImage] as? UIImage else {
                print("No image found")
                return
            }
    
            // You will get your image here
            print(image.size)
         }
    
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
            picker.dismiss(animated: true, completion: nil)
            // here you will get the cancel event
        }
    
    }
    

    【讨论】:

    • 谢谢。我正在尝试将图像存储在应用程序的缓存中,以便可以在不将其存储在用户设备上的情况下对其进行分析(安全原因)。你对如何做到这一点有任何想法吗?还有一个问题。当我尝试将其放在将打开相机的视图中时,vc.delegate = selfpresent(vc, animated: true) 行出现错误。这两个错误都表明我正在使用未解析的标识符来表示自己和存在。我在extension youViewControllerClass:... 行也收到错误消息。此错误表示我正在使用未声明的类型。有什么办法可以解决这个问题?
    • @AGoraya0710 您必须将此代码放在您拥有视图的 UIViewController 类中,因为present(vc, animated: true) 是 UIViewController 及其子类的属性。您还需要将 youViewControllerClass 替换为您的 UIViewController 的原始名称。
    • 如果这是一个愚蠢的问题,我深表歉意。我没有 UIViewController 类。我拥有的类是:PhotoCaptureView.swift、ImagePicker.swift、ContentView.swift、SceneDelegate.swift 和 AppDelegate.swift。如果您愿意,我可以链接每个内部代码的图像,但我目前没有 UIViewController 类。我应该在哪里创建这个类以及如何创建?
    • 如果您使用的是 swiftUI,您可以查看此答案,希望对您有所帮助。 [stackoverflow.com/questions/56515871/…
    猜你喜欢
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多