#ios #swift
#iOS #swift
Вопрос:
Я пытаюсь создать контроллер для обработки всех функций изображения, чтобы вы могли легко привязать все действия камеры к любому контроллеру просмотра.
В идеале моей целью было создать класс с функцией, которая возвращает UIImage и позволяет мне самостоятельно писать отдельные обработчики завершения
ie.
let imagePicker = ImagePickerAlertController(frame:self.view.frame,controller:self)
imagePicker.displayAlert(){
imageValue in if let image = imageValue {
myImageView.image = image
}
}
Однако, похоже, я не могу сохранить изображение или даже получить доступ к изображению, которое я снял с камеры. Функция imagePickerController, похоже, не работает.
import UIKit
class ImagePickerAlertController: UIView, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var UIViewController : UIViewController?
let imagePicker: UIImagePickerController! = UIImagePickerController()
init(frame: CGRect, controller: UIViewController){
self.UIViewController = controller
super.init(frame:frame)
}
required init?(coder aDecoder: NSCoder) {
self.UIViewController = nil
super.init(coder: aDecoder)
}
public func displayAlert(){
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let galleryAction = UIAlertAction(title: "Choose Photo",style:.default) {action -> Void in print("ok")}
let cameraAction = UIAlertAction(title: "Take Photo",style:.default) {action -> Void in self.takePicture() }
let cancelAction = UIAlertAction(title: "Cancel",style:.cancel) {action -> Void in }
alert.addAction(cancelAction)
alert.addAction(cameraAction)
alert.addAction(galleryAction)
self.UIViewController?.present(alert,animated:true,completion:nil)
}
private func takePicture() {
if (UIImagePickerController.isSourceTypeAvailable(.camera)){
if UIImagePickerController.availableCaptureModes(for: .rear) != nil || UIImagePickerController.availableCaptureModes(for: .front) != nil{
imagePicker.allowsEditing = false
imagePicker.sourceType = .camera
imagePicker.cameraCaptureMode = .photo
imagePicker.delegate = self
self.UIViewController?.present(imagePicker,animated: true,completion: nil)
}
else {
postAlert(title: "Rear camera doesn't exist",message:"Application cannot access the camera.")
}
}
else {
postAlert(title: "Camera inaccessable",message:"Application cannot access the camera.")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("got image")
if let pickedImage:UIImage = (info[UIImagePickerControllerOriginalImage]) as? UIImage {
let selectorToCall = Selector(("imageWasSavedSuccessfully:didFinishSavingWithError:context:"))
UIImageWriteToSavedPhotosAlbum(pickedImage, self, selectorToCall, nil)
}
imagePicker.dismiss(animated: true,completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("cancel")
self.UIViewController?.dismiss(animated: true, completion: nil)
}
func imageWasSavedSuccessfully(image: UIImage, didFinishSavingWithError error : NSError!, context: UnsafeMutablePointer<()>){
print("image saved")
if (error) != nil {
print(error)
}
else {
print("good to go")
}
}
func postAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.UIViewController?.present(alert, animated: true, completion: nil)
}
}
Ответ №1:
Проблема в том, что вы пытаетесь представить imagePicker
, когда у вас UIViewController
уже есть модальный контроллер представления, представленный выше.
DisplayAlert():
self.UIViewController?.присутствует (оповещение, анимация: истина, завершение: ноль)
takePicture():
self.UIViewController?.присутствует (выбор изображения, анимация: истина, завершение: ноль)
Поэтому вы должны отклонить UIAlertController, как только он вам не понадобится:
let cameraAction = UIAlertAction(title: "Take Photo",style:.default) {action -> Void in
alert.dismiss(animated: true, completion: nil)
self.takePicture()
}
Теперь ViewController может present
без каких-либо проблем
Комментарии:
1. Удивительные. Просто последующий вопрос. Это означает, что всегда может быть только один контроллер?
2. ДА. Там для конкретного контроллера на данный момент может быть только один vc, представленный модально. Чтобы показать новый, вам нужно отключить текущий. Однако вы можете представить другой vc поверх того, который вы уже представили, но это не лучшая практика.