class CameraPicker: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
weak var viewController:MyProfileVC!
func launchCamera() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.front
imagePicker.cameraCaptureMode = .photo
imagePicker.allowsEditing = false
self.viewController.present(imagePicker, animated: true, completion: nil)
} }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("didFinishPickingMedia")
}
这是我的对象类函数,但是' didFinishPickingMediaWithInfo'拍照后,功能不会被调用。此外,呈现imagepicker的viewcontroller是一个不同的Swift文件
答案 0 :(得分:1)
我遇到了同样的问题,我找到了一个解决方案,所以我发布了我的版本(我正在从照片库中拍照,但它是一样的:))。
我遇到了内存管理问题。 我已经创建了一个IBAction函数,我实例化了我的相机处理程序类(里面有委托......)。在函数结束时,变量超出范围并被解除分配。为了解决这个问题,我把它作为实例变量。
这是我的UiButton的VC代码:
class STECreateUserVC: UIViewController {
@IBOutlet weak var imgAvatar: UIImageView!
let cameraHandler = STECameraHandler()
@IBAction func buttonPressed(_ sender: UIButton) {
cameraHandler.importPictureIn(self) { [weak self] (image) in
self?.imgAvatar.image = image
}
}
}
......那是我的经纪人:
class STECameraHandler: NSObject {
let imagePickerController = UIImagePickerController()
var completitionClosure: ((UIImage) -> Void)?
func importPictureIn(_ viewController: UIViewController, completitionHandler:((UIImage) -> Void)?) {
completitionClosure = completitionHandler
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .photoLibrary
imagePickerController.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
viewController.present(imagePickerController, animated: true, completion: nil)
}
}
extension STECameraHandler: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let completitionClosure = completitionClosure, let image = info[UIImagePickerControllerEditedImage] as? UIImage {
completitionClosure(image)
}
imagePickerController.dismiss(animated: true)
}
}
我使用了一个闭包来获得更清晰的代码。
答案 1 :(得分:-1)
此:
self.viewController.present(imagePicker, animated: true, completion: nil)
应该是:
self.present(imagePicker, animated: true, completion: nil)