AGoraya0710
AGoraya0710

Reputation: 59

How to implement camera functionality in iOS app through XCode

I am starting from zero with iOS app development but I need to create an app that can use the iPhone camera to take an image. I have found UIImagePickerController but I cannot figure out how to implement it correctly. If anyone could help me that would be great. Also I know very little about app development so if there is any background knowledge I would need to understand your answers would be appreciated.

Upvotes: 0

Views: 825

Answers (1)

Chitra
Chitra

Reputation: 46

You can call this method wherever you want to open UIImagePickerController:

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

Make your view controller conform to both UINavigationControllerDelegate and UIImagePickerControllerDelegate by making an extension like this:

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
    }

}

Upvotes: 1

Related Questions