I want a camera interface in my app with capture and save image capabilities but i'm not able to get anything when i run this app, build is successful without any errors but nothing is showing on the viewController.
class ViewController: UIViewController , UINavigationControllerDelegate, UIImagePickerControllerDelegate{
#IBOutlet var imageView: UIImageView!
#IBOutlet var TakePhoto: UIButton!
var imagePick: UIImagePickerController!
var newMedia: Bool?
#IBAction func TakePhoto(_ sender: AnyObject){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePick = UIImagePickerController()
imagePick.delegate = self
imagePick.sourceType = UIImagePickerControllerSourceType.camera
imagePick.mediaTypes = [kUTTypeImage as String]
imagePick.allowsEditing = false
self.present(imagePick, animated: true, completion: nil)
newMedia = true
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as String){
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
if(newMedia == true){
UIImageWriteToSavedPhotosAlbum(image, self, #selector(ViewController.image(image:didFinishSavingWithError:contextInfo:)), nil)
} //else if mediaType.isEqual(to: kUTTypeMovie as String)
self.dismiss(animated: true, completion: nil)
}
}
func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafeRawPointer){
if error != nil{
let alert = UIAlertController(title: "Save Failed", message: "Failed to save the image", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
}
Have you set the permission to use camera in info.plist?
I mean to put the key Privacy - Camera Usage Description, type String with a description why are you using it
Related
ImagePickerController crashes every time when fetching a photo from the library and the warning will show like this.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x6000033a8280'
I am using UIImagePickerController
but when I'm fetching photo from the camera it works fine.
I have put this code in info.list
<key>NSCameraUsageDescription</key>
<string>This app wants to take pictures.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app wants to use your photos.</string>
this is all of my code in my viewcontroller
I want to fetch a photo from library by using ImagePickerController I don't know why it's crash.
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var shopIDNumber: UILabel!
#IBOutlet weak var bgAddImage: UIView!
#IBOutlet weak var doneButton: UIButton!
#IBOutlet weak var confirmImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tapOnImage()
shopIDNumber.layer.cornerRadius = 8
bgAddImage.layer.cornerRadius = 8
doneButton.layer.cornerRadius = 25
}
#objc func tapToImageView(sender: UITapGestureRecognizer) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.allowsEditing = true
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
pickerController.sourceType = .camera
self.present(pickerController, animated: true, completion: nil)
}else{
let alert = UIAlertController(title: "Mistake", message: "Camera Not Work", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Okey", style: .default) { (action) in
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}))
actionSheet.addAction(UIAlertAction(title: "Library", style: .default, handler: { (action) in
pickerController.sourceType = .photoLibrary
self.present(pickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
selectedImageFromPicker = editedImage
}else if let originalImage:UIImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
confirmImage.image = selectedImage
}
self.doneButton.backgroundColor = UIColor(red: 0.0, green: 182.0 / 255.0, blue: 79.0 / 255.0, alpha: 1.0)
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func tapOnImage() {
let tapGestureToImageView = UITapGestureRecognizer(target: self, action: #selector(tapToImageView(sender:)))
tapGestureToImageView.numberOfTapsRequired = 1
confirmImage?.isUserInteractionEnabled = true
confirmImage.addGestureRecognizer(tapGestureToImageView)
}
}
Your code looks fine. Most probably the issue is with following.
#IBOutlet weak var confirmImage: UIImageView!
Check if your Interface Builder is properly hooked with this outlet. Looks like it's broken or hooked into an incorrect type.
You can verify if the issue is here by commenting out following line:
confirmImage.image = selectedImage
When you comment out above line if app doesn't crash, my original assumption is correct.
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)
}
I am trying to record video and then save it on an IOS device, I am able to record it but I am wondering how to save it on the device?
import UIKit
import AVKit
import MobileCoreServices
class ViewController: UIViewController , UIImagePickerControllerDelegate , UINavigationControllerDelegate {
#IBOutlet weak var RecordButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func RecordAction(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
print("Camera Available")
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.mediaTypes = [kUTTypeMovie as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
} else {
print("Camera UnAvaialable")
}
}
}
First make sure to add below Privacies to info.plist :
Privacy - Photo Library Additions Usage Description
Privacy - Camera Usage Description
Privacy - Microphone Usage Description
and add below functions under ViewDidLoad
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
dismiss(animated: true, completion: nil)
guard
let mediaType = info[UIImagePickerControllerMediaType] as? String,
mediaType == (kUTTypeMovie as String),
let url = info[UIImagePickerControllerMediaURL] as? URL,
UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path)
else {
return
}
// Handle a movie capture
UISaveVideoAtPathToSavedPhotosAlbum(
url.path,
self,
#selector(video(_:didFinishSavingWithError:contextInfo:)),
nil)
}
#objc func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo info: AnyObject) {
let title = (error == nil) ? "Success" : "Error"
let message = (error == nil) ? "Video was saved" : "Video failed to save"
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
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)
}
}}
Im trying to learn how to access and use the camera on IOS devices, trufully i cant find all that much info on it, at least not thats up to date or useful to learn at a beginner level.
Regardless, I've tried the below code but nothing happens when I click the button to open the camera it just freezes and does nothing, am i missing something or have i done something wrong?
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var myImg: UIImageView!
var newMedia: Bool!
#IBAction func cameraRoll(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
newMedia = false
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
self.dismiss(animated: true, completion: nil)
if mediaType.isEqual(to: kUTTypeImage as String){
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
myImg.image = image
if (newMedia == true) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(ViewController.image(image:didFinishsavingWithError:contextInfo:)), nil)
} else if mediaType.isEqual(to: kUTTypeMovie as String){
//vid support
}
}
}
func image(image: UIImage, didFinishsavingWithError error: NSErrorPointer, contextInfo:UnsafeRawPointer){
if error != nil {
let alert = UIAlertController(title: "Save Failed", message: "Failed to save image", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func takePhoto(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
newMedia = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}