How to take and save photo without Uiimageview (swift4) - ios

The following code is that standard take photo then place it on imagview then save the image on image view to the photo gallery. I want to skip the uiimageview part and just take photo and have it automatically save to the photo gallery.
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var imagePicker: UIImagePickerController!
#IBOutlet weak var imageTake: UIImageView!
#IBAction func takePhoto(_ sender: AnyObject) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
#IBAction func save(_ sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(imageTake.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
#objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imagePicker.dismiss(animated: true, completion: nil)
imageTake.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
}

Then you can do the following edit
#IBAction func save(_ sender: AnyObject) {
/// useless now
}
#objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imagePicker.dismiss(animated: true, completion: nil)
if let img = info[UIImagePickerControllerOriginalImage] as? UIImage
{
UIImageWriteToSavedPhotosAlbum(img, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
}}

Related

Swift 4 Image Picker Not Changing UIImageView

For some reason in my new project this code is not working which has worked for me before. The current code does not change the ui of profileImage.
Delegates
UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate
Code:
#IBOutlet weak var profileImage: UIImageView!
#IBAction func changeProfilePicture(_ sender: Any) {
print("Profile picture tapped")
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.allowsEditing = true
let alertController = UIAlertController(title: "Add Picture", message: "", preferredStyle: .actionSheet)
let photoLibraryAction = UIAlertAction(title: "Photo 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(photoLibraryAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : Any]?) {
self.profileImage.image = image
self.dismiss(animated: true, completion: nil)
}
Console Output
errors encountered while discovering extensions: Error
Domain=PlugInKit Code=13 "query cancelled"
UserInfo={NSLocalizedDescription=query cancelled}
I have tried
#objc func
internal func
#objc internal func
self.profileImage.image = image does not set the UI and change the image
Correct delegate method
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
self.profileImage.image = image
}
else
if let image = info[.editedImage] as? UIImage {
self.profileImage.image = image
}
self.dismiss(animated: true, completion: nil)
}

alert view to pick camera or gallery doesn't pop up in swift 4

I have a viewcontroller with navigation controller. I have button for uploading images.But after pressing the button it doesn't popup the alert for camera or photo library options although i have written codes for alert. Why doesn't the alert popup appear? I have also given Privacy - Photo Library Usage Description in info.plist. My code is given :
import UIKit
import Alamofire
class ProfilePicController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagePicker = UIImagePickerController()
#IBOutlet weak var uploadPic: UIButton!
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
profilePic.layer.cornerRadius = profilePic.frame.size.width / 2
profilePic.clipsToBounds = true
// Do any additional setup after loading the view.
}
#IBAction func uploadPic(_ sender: Any) {
print("image add")
let alert = UIAlertController(title: nil, message: "Choose your source", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("Camera selected")
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
})
alert.addAction(UIAlertAction(title: "Photo library", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("Photo selected")
self.imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
})
self.present(self.imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profilePic.image = selectedImage
// self.savePic()
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
//Alert.swift file
import UIKit
class Alert {
class func showBasic(title: String ,message: String , vc: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(defaultAction)
vc.present(alert, animated: true, completion: nil)
}
}
Actually you don't present the alert
#IBAction func uploadPic(_ sender: Any) {
print("image add")
let alert = UIAlertController(title: nil, message: "Choose your source", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Camera", style: .default) { (result : UIAlertAction) -> Void in
print("Camera selected")
self.imagePicker.sourceType = .camera
self.present(self.imagePicker, animated: true, completion: nil)
})
alert.addAction(UIAlertAction(title: "Photo library", style: .default) { (result : UIAlertAction) -> Void in
print("Photo selected")
self.imagePicker.sourceType = .photoLibrary
self.present(self.imagePicker, animated: true, completion: nil)
})
self.present(alert, animated: true, completion: nil)
}

How to get the image picker in (swift 3) to switch back and 4th between photo gallery and camera.

This code allows access to my photo gallery on the iPhone simulator in Xcode. When I put it on my iPad I can access the camera but not the photo gallery. I would like the image view to display the camera photos if choose or load a image from the photo gallery if choose.
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let picker = UIImagePickerController()
#IBOutlet weak var iv: UIImageView!
#IBAction func cameraf(_ sender: UIBarButtonItem) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.cameraCaptureMode = .photo
picker.modalPresentationStyle = .fullScreen
present(picker,animated: true,completion: nil)
} else {
noCamera()
}}
#IBAction func photolibaryss(_ sender: UIBarButtonItem) {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
picker.modalPresentationStyle = .popover
present(picker, animated: true, completion: nil)
picker.popoverPresentationController?.barButtonItem = sender
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
var chosenImage = UIImage()
chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
iv.contentMode = .scaleAspectFit
iv.image = chosenImage
dismiss(animated:true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
Update to the answer above. It works great, but has a few typos - need closing parentheses on addActions. Xcode 8.2 also changed presentViewController to present.
let alert = UIAlertController(title: nil, message: "Choose your source", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Camera selected")
//Code for Camera
//cameraf
})
alert.addAction(UIAlertAction(title: "Photo library", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Photo selected")
//Code for Photo library
//photolibaryss
})
self.present(alert, animated: true, completion: nil)
You can make a UIAlertController which would consist of two alert actions photo library and camera, and then add the functions lines of code from photolibaryss and cameraf to respective alert actions.
let alert = UIAlertController(title: nil, message: "Choose your source", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Camera selected")
//Code for Camera
//cameraf
})
alert.addAction(UIAlertAction(title: "Photo library", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Photo selected")
//Code for Photo library
//photolibaryss
})
self.present(alert, animated: true, completion: nil)

Unable to pass image taken from camera to another viewcontroller

I have a button to take an image . I wish to pass the image taken from camera to another view controller.The code for first viewcontroller is shown below.
#IBAction func takePhoto(sender: AnyObject)
{ let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true,completion : nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
TakenImage = info[UIImagePickerControllerOriginalImage] as? UIImage ; dismissViewControllerAnimated(true, completion: nil )
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("NoteDetailViewController") as! NoteDetailViewController
controller.takinPhoto = true
if (note != "")
{
controller.content = note
}
controller.imageFromCamera = TakenImage
if (self.tags != "")
{
controller.tagsTextField.text = self.tags
}
self.presentViewController(controller, animated: true, completion: nil)
}
#IBAction func save(sender: AnyObject)
{
UIImageWriteToSavedPhotosAlbum(TakenImage!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>)
{
if error == nil {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
} else
{
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
The code for my second viewcontroller is shown below
if (takinPhoto == true)
{
if (imageFromCamera != nil)
{
if let image1 = self.imageFromCamera
{
self.imageView2.image = image1
}
}
if (self.content != "")
{
self.contentTextField2.text = content
}
}
But image from camera is not appearing in the second viewcontroller.How can I solve this??
Updated answer.
I rewrote your code and was able to get it working locally. The main change was to use a different delegate method which is specific to photos.
#IBAction func takePhoto(sender: AnyObject) { let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true,completion : nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
takenImage = image
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func save(sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(takenImage!, self, #selector(ViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error == nil {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
} else {
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "saveTakenImage") {
let controller = segue.destinationViewController as! NoteDetailViewController
controller.takinPhoto = true
if (note != "") {
controller.content = note
}
controller.imageFromCamera = takenImage
if (self.tags != "") {
controller.tagsTextField.text = self.tags
}
}
}

Include UIImagePickerController in a view

I need to make a view that works like pages, with a popup in which I can choose to pick a photo from my library or create a new one.
Currently, I have a ViewController, present as Popover. In the ViewController, I inserted a ContainerView and I declared that its class is UIImageViewController. This is showing me the photo library but I don't find how to pick anything in : My ViewController presented as Popover.
When I choose a photo, nothing's happening. I've tried to put some functions
(func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!))
in my ViewController but it does not work. I've read that UIImagePickerController does not support subclassing, so how Pages do this stuff ?
Here is my ViewController code :
import UIKit
class MenuAddResources: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var newMedia: Bool?
let imagePicker = UIImagePickerController()
#IBAction func takePhoto(sender: AnyObject) {
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
//load the camera interface
let picker : UIImagePickerController = UIImagePickerController()
picker.sourceType = UIImagePickerControllerSourceType.Camera
picker.delegate = self
picker.allowsEditing = false
self.presentViewController(picker, animated: true, completion: nil)
self.newMedia = true
}
else{
//no camera available
let alert = UIAlertController(title: NSLocalizedString("ERROR", comment: ""), message: NSLocalizedString("NO_CAMERA", comment: ""), preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .Default, handler: {(alertAction)in
alert.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) {
if error != nil {
let alert = UIAlertController(title: NSLocalizedString("ERROR", comment: ""), message: NSLocalizedString("IMAGE_SAVE_FAILED", comment: ""), preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .Cancel, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
// Let's store the image
let now:Int = Int(NSDate().timeIntervalSince1970)
let imageData = UIImageJPEGRepresentation(image, 85)
//imageData?.writeToFile(documentsDirectory + "/\(now).jpg", atomically: true)
print(imageData)
/* will do stuff with the image */
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
It appears you are using UIImagePickerViewController through a
container view and therefore the delegate isnt set , thus no callbacks
to receiving the image picked methods.
To fix this, you must override prepareForSegue in your class
and in that cast the segue.destinationViewController to your picker and set its delegate to self

Resources