I am new to programming in general and was having trouble with memory leak problems with the following code specifically involving the "imagePickerController." The leaks only occur after the UIimagePickerController is dismissed after selecting an image. Thank you for any help fixing this.
let imagePicked = UIImagePickerController()
@IBAction func addPhoto(_ sender: UIBarButtonItem) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.allowsEditing = false
imagePicked.delegate = self
let alertController = UIAlertController(title: "Add New Image", message: "Choose From", preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .default) { (action) in
pickerController.sourceType = .camera
self.present(pickerController, animated: true, completion: nil)
}
let photosLibraryAction = UIAlertAction(title: "Photos Library", style: .default) { (action) in
pickerController.sourceType = .photoLibrary
self.present(pickerController, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
alertController.addAction(cameraAction)
alertController.addAction(photosLibraryAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
var newImageView = UIImageView()
newImageView = UIImageView(image: image)
newImageView.contentMode = .scaleAspectFit
newImageView.center = textView.center
textView.addSubview(newImageView)
}
dismiss(animated: true, completion: nil)
}
EDIT ONE:
Thank you I have removed @objc
in front of didFinishPickingMediaWithInfo
as well as the extra UIImagePickerController
object, but I am still having the same problem. I have also tried picker.dismiss(animated: true, completion: nil)
but that is still not fixing the problem.
And yes I am pretty sure it is a memory leak error as I've ran the tester and after putting pictures into the app from the photos library or the camera I am getting this: picture 1 picture 2
Also after adding several pictures the app will crash with "Terminated due to memory problem"