Last active
February 18, 2019 03:52
-
-
Save Xopoko/93baa6160c3f04c281605ce41100c1c3 to your computer and use it in GitHub Desktop.
Easily trigger the camera and take a picture with completion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CameraManager: NSObject { | |
static let shared: CameraManager = { | |
let instance = CameraManager() | |
return instance | |
}() | |
private var completions = [((UIImage?) -> Void, UIImagePickerController)]() | |
@discardableResult | |
func present(animated: Bool = true, on viewController: UIViewController? = nil, with completion: @escaping (UIImage?) -> Void) -> UIViewController? { | |
guard let vc = viewController ?? UIApplication.shared.keyWindow?.rootViewController else { | |
print("CameraManager error: rootViewController is not in the window hierarchy") | |
return nil | |
} | |
guard UIImagePickerController.isSourceTypeAvailable(.camera) else { | |
print("CameraManager error: Device does not supported") | |
return nil | |
} | |
let pickerController = UIImagePickerController() | |
pickerController.delegate = self | |
pickerController.sourceType = .camera | |
completions.append((completion, pickerController)) | |
vc.present(pickerController, animated: animated, completion: nil) | |
return vc | |
} | |
} | |
extension CameraManager: UIImagePickerControllerDelegate, UINavigationControllerDelegate { | |
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { | |
let completion = completions.first { $0.1 == picker } | |
let image = info[UIImagePickerControllerOriginalImage] as? UIImage | |
completion?.0(image) | |
} | |
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { | |
let completion = completions.first { $0.1 == picker } | |
completion?.0(nil) | |
completions.removeAll(where: { $0.1 == completion?.1}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment