How to allow user to pick the image with Swift?
If you just want let the user choose image with UIImagePickerController use this code:
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var imageView: UIImageView!
@IBOutlet var chooseBuuton: UIButton!
var imagePicker = UIImagePickerController()
@IBAction func btnClicked() {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
print("Button capture")
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
self.dismiss(animated: true, completion: { () -> Void in
})
imageView.image = image
}
}
How can I allow a user to pick an image from their apple device?
In Swift 4.2, the delegate method has been changed to:
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
And UIImagePickerControllerOriginalImage
has been renamed to UIImagePickerController.InfoKey.originalImage
.
You should change your method signature and the name you use for the key. Your code should work fine.
How to allow the user to pick a photo from his camera roll or photo library?
I worked on an application that allows user to select a personal image. I had two UIButtons which could help the user to pick a picture, whether it was from camera or library. It's something like this:
- (void)camera {
if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
return;
}
UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//Permetto la modifica delle foto
picker.allowsEditing = YES;
//Imposto il delegato
[picker setDelegate:self];
[self presentModalViewController:picker animated:YES];
}
- (void)library {
//Inizializzo la classe per la gestione della libreria immagine
UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//Permetto la modifica delle foto
picker.allowsEditing = YES;
//Imposto il delegato
[picker setDelegate:self];
[self presentModalViewController:picker animated:YES];
}
You have to implement the UIImagePickerControllerDelegate:
@interface PickPictureViewController : UIViewController <UIImagePickerControllerDelegate>
@implementation PickPictureViewController
#pragma mark UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *pickedImage = [info objectForKey:UIImagePickerControllerEditedImage];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(pickedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
[self dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[self dismissModalViewControllerAnimated:YES];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{}
Hope it helps! ;)
Allow the user to choose the profile picture he wants and change whenever he wants
If i am not Wrong You want the Image to be Stored in As it if also the User sign out from app.
You can possibly Store the Image in Document Directory
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
let newPath = path.appendingPathComponent("image.jpg") //Possibly you can Use the UserName to fetch easily User-wise
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
do {
try jpgImageData!.write(to: newPath)
} catch {
print(error)
}
}
}
To Fetch the Image Back:-
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image.png")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}
Hope this Helps you.
You can use Scenario Like. Initially The image view will be Empty.
- User will select the image using picker View.
- It will be stored in Document Directory
- User Log out from App
- User log in back to app(At that time check if any image is there with the users name then fetch from Document directory and directly
show or else blank) - User can change profile picture and step 1-4 Repeated
Edited : Integrated in you Code:
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var imageView: UIImageView!
@IBOutlet var chooseBuuton: UIButton!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
//Check if image exist in Document Directory
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image.png")
let image = UIImage(contentsOfFile: imageURL.path)
imageView.image = image
}else{
// Image not present
// Do whatever you want to do here
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
self.dismiss(animated: true, completion: { () -> Void in
})
imageView.image = image
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = image
imageView.contentMode = .scaleAspectFill
let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
let newPath = path.appendingPathComponent("image.jpg") //Possibly you can Use the UserName to fetch easily User-wise
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
do {
try jpgImageData!.write(to: newPath)
} catch {
print(error)
}
}
dismiss(animated: true, completion: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = .photoLibrary
present(controller, animated: true, completion: nil)
}}
Possibly This would help You. Let me know if it works
Allowing user to select image from Camera, Photo Library or Photo Albums and hit an error I cannot solve
I've answered my own question!
the extension class ViewController was incorrectly named. My .swift file was named something else.
I also moved the UIImageViewControllerDelegate and the UINavigatonControllerDeletage from the original class at the top of the code so it only appeared in the extension!
Swift 3: How to allow users to select multiple images from photo library?
How to install frameworks/projects via CocoaPods ?
Answer
Try to install cocoaPods
:
$ sudo gem install cocoapods
Go to your project folder:
pod init
A file called podfile will be created in your project folder.
Edit that file:
pod 'YangMingShan'
After that run:
pod install
Remember to open the generated workspace file after that.
How to make UIImagePickerController for camera and photo library at the same time in swift
Import UIImagePickerControllerDelegate
and create a variable to assign UIImagePickerControllervar imagePicker = UIImagePickerController()
and set imagePicker.delegate = self
.
Create an action sheet to display options for 'Camera' and 'Photo library'.
On your button click action:
@IBAction func buttonOnClick(_ sender: UIButton)
{
self.btnEdit.setTitleColor(UIColor.white, for: .normal)
self.btnEdit.isUserInteractionEnabled = true
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
/*If you want work actionsheet on ipad
then you have to use popoverPresentationController to present the actionsheet,
otherwise app will crash on iPad */
switch UIDevice.current.userInterfaceIdiom {
case .pad:
alert.popoverPresentationController?.sourceView = sender
alert.popoverPresentationController?.sourceRect = sender.bounds
alert.popoverPresentationController?.permittedArrowDirections = .up
default:
break
}
self.present(alert, animated: true, completion: nil)
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera))
{
imagePicker.sourceType = UIImagePickerController.SourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallary()
{
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
Download sample project for Swift, SwiftUI
Related Topics
Swift Version of Componentsseparatedbystring
Swift 3: Type 'Any' Has No Subscript Members
Xcode iOS Project Only Shows "My MAC 64-Bit" But Not Simulator or Device
Adjust Uibutton Font Size to Width
First App Update, User Data Lost (Was Stored in Documents Directory)
Missing Cfbundleiconname in Xcode9 iOS11 App Release
iOS Gps Tracking App That Runs All the Time
How to Disable Control Center in iOS 7 Programmatically and If Not, What Are Alternatives
Linker Error in iOS (Duplicate Symbols for Architecture X86_64)
Xcode 7.3.1 with iOS 10 Support
Use a Generic Class as a Custom View in Interface Builder
Firebase Cloud Messaging - Send Message to All Users
Uiview - How to Get Notified When the View Is Loaded
Objective-C 101 (Retain VS Assign) Nsstring
Auto Layout Uiscrollview with Subviews with Dynamic Heights
Swift - Uibutton with Two Lines of Text