ios - 如何用Swift编程实现自动拍照?

标签 ios iphone swift camera

我正在使用 iPhone 摄像头使用 Swift 进行开发。

我使用以下代码来检查相机:

if UIImagePickerController.isSourceTypeAvailable(.Camera) {   
    let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = UIImagePickerControllerSourceType.Camera
        picker.allowsEditing = true  
        self.presentViewController(picker, animated: true)
    } else {
        print("can't find camera")
    }
}

然后我使用以下代码打开相机。

presentViewController(imagePicker, animated: true, completion: nil)

我引用了以下 link并调用 takePicture() ,但它似乎没有工作。

但我总是需要通过点击快门按钮手动拍照。在 Swift 中以编程方式拍摄照片是否可行?

提前致谢。

最佳答案

1) 检查你的 View Controller 类中是否有这些委托(delegate):

 UIImagePickerControllerDelegate, UINavigationControllerDelegate

2) 检查你的 plist 是否有 YES 的权限

Privacy - Photo Library Usage Description
Privacy - Camera Usage Description

如果你愿意,我使用这段代码(swift 3):

    let imagePicker = UIImagePickerController()
    imagePicker.sourceType = .photoLibrary
    imagePicker.delegate =  self
    self.present(imagePicker, animated: true, completion: nil)

对于相机,只需更改“photoLibrary”

    imagePicker.sourceType = .camera

3) 为了获取图片,必须实现委托(delegate)didFinishPickingMediaWithInfo:

extension YourViewController: 
                             UIImagePickerControllerDelegate, 
                             UINavigationControllerDelegate 
{

  func imagePickerController(
              _ picker:                           UIImagePickerController,  
              didFinishPickingMediaWithInfo info: [String : Any]) 
  {
    imagePicker.dismiss(animated: true, completion: nil)
    let image = info[UIImagePickerControllerOriginalImage] as? UIImage
    print("picture taken: \(image)")
  }
}

关于ios - 如何用Swift编程实现自动拍照?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36862051/

相关文章:

ios - 将 JSON 输出存储在 NSArray 中

iphone - release 与 nil —— 最佳实践

iOS 调整 UITableheaderView 的大小

iphone - 关于如何实现图像幻灯片/轮播的建议? ( iOS )

objective-c - 将 NSData objectiveC 代码转换为 swift 时出错

IOS核心蓝牙: Writing NSData for Characteristic

ios - 滚动 UIViewController 标题

ios - 在运行时更新 label.text

swift - 在运行时更改 SkspriteNode PhysicsBody 大小

ios - 为什么TableView、TableCell不出现?