我有一个有两个选项的操作表:一个可以从库中选择图像,另一个可以从相机中拍摄照片。照片库功能正常,但我似乎无法让相机工作。
这是我的代码:
let takePhoto = UIAlertAction(title: "Take photo", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
// present camera taker
var cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .Camera
self.presentViewController(cameraPicker, animated: true, completion: nil)
})
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
var selectedAvatar = UIImagePickerControllerOriginalImage
self.dismissViewControllerAnimated(false, completion: nil)
}
我似乎无法找到问题,任何人都可以帮助我吗?当我尝试运行它并单击拍照时,程序崩溃。
答案 0 :(得分:6)
您最有可能在模拟器中运行。模拟器没有相机,所以在按下按钮时不要让应用程序崩溃,你必须检查cemera是否可用。
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
...
}
else {
print("Sorry cant take picture")
}
答案 1 :(得分:1)
按照以下代码
func takePhoto()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
{
picker!.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(picker!, animated: true, completion: nil)
}
else
{
let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
alertWarning.show()
}
}
func openGallary()
{
picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(picker!, animated: true, completion: nil)
}
//PickerView Delegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
picker .dismissViewControllerAnimated(true, completion: nil)
imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
println("picker cancel.")
}
答案 2 :(得分:0)
另一个原因是,当Kirit Modi在下面的步骤中说到相机在真实设备中使用时可能会崩溃:
iOS 10 - App crashes To access photo library or device camera via UIImagePickerController
在iOS 10中。您必须为相机和相机设置隐私设置。图片库。相机& info.Plist上的照片隐私设置
这解决了我崩溃的问题!