How can i load photo from camera or phone library to parse, like PFFile?
How to load image from assets i know, my code:
func loadImage() {
let query = PFQuery(className: "_User")
query.findObjectsInBackground { (objects, error) in
let firstObject = objects?.first as PFObject?
let objectFile = firstObject?.object(forKey: "avatar") as! PFFile
objectFile.getDataInBackground(block: { (imageData, error) in
let image = UIImage(data: imageData!)
if image != nil {
self.avatar.image = image
}
})
}
}
This code upload image from assets.
But i need upload from camera or library.
Try this.
call displayUploadImageDialog func on button click. it will open dialog and when you select any image from photos than below delegate method calls.
func displayUploadImageDialog(btnSelected: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
let alertController = UIAlertController(title: "", message: "Action on Upload", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel action"), style: .cancel, handler: {(_ action: UIAlertAction) -> Void in
alertController.dismiss(animated: true) {() -> Void in }
})
alertController.addAction(cancelAction)
let takePhotoAction = UIAlertAction(title: NSLocalizedString("Take Photo", comment: "Take Photo action"), style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UI_USER_INTERFACE_IDIOM() == .pad {
OperationQueue.main.addOperation({() -> Void in
picker.sourceType = .camera
self.present(picker, animated: true) {() -> Void in }
})
}
else {
if !UIImagePickerController.isSourceTypeAvailable(.camera) {
let passwordAlert = UIAlertController(title: "Error", message: "Device has no camera", preferredStyle: .alert)
let yesButton = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
//Handel your yes please button action here
passwordAlert.dismiss(animated: true) {() -> Void in }
})
passwordAlert.addAction(yesButton)
self.present(passwordAlert, animated: true) {() -> Void in }
}
else {
picker.sourceType = .camera
self.present(picker, animated: true) {() -> Void in }
}
}
})
alertController.addAction(takePhotoAction)
let cameraRollAction = UIAlertAction(title: NSLocalizedString("Camera Roll", comment: "Camera Roll action"), style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UI_USER_INTERFACE_IDIOM() == .pad {
OperationQueue.main.addOperation({() -> Void in
picker.sourceType = .photoLibrary
self.present(picker, animated: true) {() -> Void in }
})
}
else {
picker.sourceType = .photoLibrary
self.present(picker, animated: true) {() -> Void in }
}
})
alertController.addAction(cameraRollAction)
alertController.view.tintColor = Colors.NavTitleColor
present(alertController, animated: true) {() -> Void in }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var user = PFUser.current()
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageData = UIImageJPEGRepresentation(image, 0.05)
let imageFile = PFFile(name:"image.jpg", data:imageData!)
user!["profilePicture"] = imageFile;
user?.saveInBackground(block: nil)
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
Related
I upload the image when button 1 is clicked, but the second image also shows the image uploaded by button 1!
What should I do so that the image uploaded on button 1 is displayed on image 1, and the image on the boat on button 2 is displayed on image 2?
Here is my code, thanks for your help
#IBAction func imageSelect(sender: Any){
let actionSheetController = UIAlertController()
let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
print("Tap 取消 Button")
}
let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
self.getImageGo(type: 1)
}
let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
self.getImageGo(type: 2)
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(takingPicturesAction)
actionSheetController.addAction(photoAlbumAction)
actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
//显示
self.present(actionSheetController, animated: true, completion: nil)
}
#IBAction func imageSelect2(sender: Any){
let actionSheetController = UIAlertController()
let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
print("Tap 取消 Button")
}
let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
self.getImageGo(type: 1)
}
let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
self.getImageGo(type: 2)
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(takingPicturesAction)
actionSheetController.addAction(photoAlbumAction)
//iPad设备浮动层设置锚点
actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
//显示
self.present(actionSheetController, animated: true, completion: nil)
}
func getImageGo(type:Int){
takingPicture = UIImagePickerController.init()
if(type==1){
takingPicture.sourceType = .camera
//takingPicture.showsCameraControls = true
}else if(type==2){
takingPicture.sourceType = .photoLibrary
}
takingPicture.allowsEditing = true
takingPicture.delegate = self
present(takingPicture, animated: true, completion: nil)
}
I think the problem is here in the code, but I don't know how to modify it, thanks for your help
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
takingPicture.dismiss(animated: true, completion: nil)
if(takingPicture.allowsEditing == false){
//原图
ID1.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
ID2.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}else{
//截图
ID1.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
ID2.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
}
}
I'm trying to access both the camera and photo library in swift4 using the following code
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let alert = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action: UIAlertAction) in
imagePickerController.sourceType = .camera
print(1)
}))
alert.addAction(UIAlertAction(title: "Photo Album", style: .default, handler: {(action: UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
but it's not working. I'm not get an access authorization request even though I made sure that the plist has the camera and photo library authorization. I manipulate the code a bit to the following
AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in
}
let photos = PHPhotoLibrary.authorizationStatus()
if photos == .notDetermined {
PHPhotoLibrary.requestAuthorization({status in
})
}
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let alert = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action: UIAlertAction) in
imagePickerController.sourceType = .camera
print(1)
}))
alert.addAction(UIAlertAction(title: "Photo Album", style: .default, handler: {(action: UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
Now I am getting the authorization request for both cameras and photo library and I can see the AlertView but when I press camera or Photo Album as shown in the picture nothing happens.
I tried on a device and simulator for the camera.
Here is the code to load image from photos & camera in iOS.
⁃ You need to create an outlet of your UIImageView
⁃ Then add a tap gesture on to image view
⁃ Then connect tap gesture with the didTapOnImageView function.
⁃ Then add the following extension to your view controller.
//MARK:- Image Picker
extension YourViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//This is the tap gesture added on my UIImageView.
#IBAction func didTapOnImageView(sender: UITapGestureRecognizer) {
//call Alert function
self.showAlert()
}
//Show alert to selected the media source type.
private func showAlert() {
let alert = UIAlertController(title: "Image Selection", message: "From where you want to pick this image?", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action: UIAlertAction) in
self.getImage(fromSourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Photo Album", style: .default, handler: {(action: UIAlertAction) in
self.getImage(fromSourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
//get image from source type
private func getImage(fromSourceType sourceType: UIImagePickerController.SourceType) {
//Check is source type available
if UIImagePickerController.isSourceTypeAvailable(sourceType) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = sourceType
self.present(imagePickerController, animated: true, completion: nil)
}
}
//MARK:- UIImagePickerViewDelegate.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
self.dismiss(animated: true) { [weak self] in
guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
//Setting image to your image view
self?.profileImgView.image = image
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
Note: Don't forget to add the privacy settings in info.plist
Privacy - Camera Usage Description
Privacy - Photo Library Usage Description
First of all, you need to import these libraries:
import Photos
import UIKit
#IBOutlet weak var loadPhoto: UIButton!
And you need setup delegates:
class YourClass: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UNUserNotificationCenterDelegate
func displayUploadImageDialog(btnSelected: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
let alertController = UIAlertController(title: "", message: "Upload profile photo?".localized(), preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel action"), style: .cancel, handler: {(_ action: UIAlertAction) -> Void in
alertController.dismiss(animated: true) {() -> Void in }
})
alertController.addAction(cancelAction)
let cameraRollAction = UIAlertAction(title: NSLocalizedString("Open library".localized(), comment: "Open library action"), style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UI_USER_INTERFACE_IDIOM() == .pad {
OperationQueue.main.addOperation({() -> Void in
picker.sourceType = .photoLibrary
self.present(picker, animated: true) {() -> Void in }
})
}
else {
picker.sourceType = .photoLibrary
self.present(picker, animated: true) {() -> Void in }
}
})
alertController.addAction(cameraRollAction)
alertController.view.tintColor = .black
present(alertController, animated: true) {() -> Void in }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
profileImage.image = image
let imageData = UIImageJPEGRepresentation(image, 0.05)
self.dismiss(animated: true, completion: nil)
}
func checkPermission() {
let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch authStatus {
case .authorized:
self.displayUploadImageDialog(btnSelected: self.loadPhoto)
case .denied:
print("Error")
default:
break
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
func checkLibrary() {
let photos = PHPhotoLibrary.authorizationStatus()
if photos == .authorized {
switch photos {
case .authorized:
self.displayUploadImageDialog(btnSelected: self.loadPhoto)
case .denied:
print("Error")
default:
break
}
}
}
Setup action for button:
#IBAction func loadPhotoTapped(_ sender: UIButton) {
let photos = PHPhotoLibrary.authorizationStatus()
if photos == .notDetermined {
PHPhotoLibrary.requestAuthorization({status in
if status == .authorized{
print("OKAY")
} else {
print("NOTOKAY")
}
})
}
checkLibrary()
checkPermission()
}
At the Info.plist setup the permissions:
Privacy - Media Library Usage Description
Privacy - Photo Library Usage Description
Privacy - Camera Usage Description
This should work.
I have a UIActionSheet for selecting between the camera or the photo library to embed an image into a UITextView but for whatever reason it's loading the keyboard. I force close the keyboard on press of the left button of the bar surrounding the UITextView but when I press photo library I opens and closes the keyboard before pushing to the image picker VC.
override func didPressLeftButton(sender: AnyObject?) {
let cameraMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let photoLibrary = UIAlertAction(title: "Photo Library", style: .Default, handler: { (UIAlertAction) in
self.openPhotoLibrary()
})
let takePhoto = UIAlertAction(title: "Open Camera", style: .Default, handler: { (UIAlertAction) in
self.textView.endEditing(true)
self.openCamera()
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
cameraMenu.addAction(photoLibrary)
cameraMenu.addAction(takePhoto)
cameraMenu.addAction(cancel)
self.presentViewController(cameraMenu, animated: true, completion: nil)
}
func openPhotoLibrary() {
imagePicker.sourceType = .PhotoLibrary
imagePicker.allowsEditing = false
presentViewController(imagePicker, animated: true, completion: nil)
}
func openCamera(){
imagePicker.sourceType = .Camera
imagePicker.showsCameraControls = true
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Image resizing
let textViewWidth: CGFloat = self.textView.frame.size.width - 20
let percentResize = textViewWidth / pickedImage.size.width
let toBeExportedHeight = pickedImage.size.height * percentResize
let resizedImage = ImageManipulationManager.sharedInstance.resizeImage(exportedWidth: Int(textViewWidth),exportedHeight: Int(toBeExportedHeight), originalImage: pickedImage)
// Storage into TextView
let attachment = NSTextAttachment()
attachment.image = resizedImage
let attString = NSAttributedString(attachment: attachment)
textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
pastedImageLocations.append(textView.selectedRange.location)
textView.selectedRange.location = textView.selectedRange.location + 1
textView.textStorage.insertAttributedString(NSAttributedString(string: "\n"), atIndex: textView.selectedRange.location)
textView.selectedRange.location = textView.selectedRange.location + 1
textView.font = UIFont.systemFontOfSize(16.0)
// Image Caching
if let data = UIImageJPEGRepresentation(pickedImage, 0.50) {
socketMessages.append(["data": data])
haneke.set(value: data, key: String(unsafeAddressOf(attachment.image!)))
print("Image cached as \"\(String(unsafeAddressOf(attachment.image!)))\"")
}
}
dismissViewControllerAnimated(true, completion: nil)
self.textView.becomeFirstResponder()
}
Found the solution.
I had to change
dismissViewControllerAnimated(true, completion: nil)
self.textView.becomeFirstResponder()
to
dismissViewControllerAnimated(true) {
self.textView.becomeFirstResponder()
}
You can do some changes by adding this -
override func didPressLeftButton(sender: AnyObject?) {
let cameraMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let photoLibrary = UIAlertAction(title: "Photo Library", style: .Default, handler: { (UIAlertAction) in
self.view.endEditing(true) //**------ Add this
self.openPhotoLibrary()
})
let takePhoto = UIAlertAction(title: "Open Camera", style: .Default, handler: { (UIAlertAction) in
self.view.endEditing(true) //**------ Add this
self.openCamera()
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
cameraMenu.addAction(photoLibrary)
cameraMenu.addAction(takePhoto)
cameraMenu.addAction(cancel)
self.presentViewController(cameraMenu, animated: true, completion: nil)
}
I want the user to choose a photo from his photo library or camera. I couldn't find any example of it. I want to prompt the user with something like UIAlertView.
My code works fine with photo library.
#IBAction func selectLeftPhoto(sender: AnyObject) {
flag = 1
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
#IBAction func selectRightButton(sender: AnyObject) {
flag = 2
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
if flag == 1 {
leftImage.image = pickedImage
let imageData = UIImageJPEGRepresentation(pickedImage!, 0.5)
let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
photo1 = base64String
}else if flag == 2 {
rightImage.image = pickedImage
let imageData = UIImageJPEGRepresentation(pickedImage!, 0.5)
let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
photo2 = base64String
}
dismissViewControllerAnimated(true, completion: nil)
}
My user interface :
I want to prompt the user to choose from the photo library or camera after clicking the select photo button.
let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openCamera()
}
let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openGallary()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
}
// Add the actions
picker?.delegate = self
alert.addAction(cameraAction)
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
// Present the controller
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
self.presentViewController(alert, animated: true, completion: nil)
}
else
{
popover=UIPopoverController(contentViewController: alert)
popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
let optionMenu = UIAlertController(title: nil, message: "Choose Option for Image", preferredStyle: .ActionSheet)
// 2
let cameraAction = UIAlertAction(title: "Camera", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
flag = 1
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(myPickerController, animated: true, completion: nil)
})
let photoGalleryAction = UIAlertAction(title: "Photo Li", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
flag = 2
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
})
//
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
println("Cancelled")
})
I am developing a chat app. In my app when I click attachement button, two options should come.
1) images/videos captured by the device camera(not capturing image at that time. Fetch images taken by the camera that is stored in the device)
2) images/videos downloaded from the web or other medias
Is there any way to fetch images/videos according to the above given criteria preferably using assets library
class YourController : UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate,UIPopoverPresentationControllerDelegate
{
override func viewDidLoad() {
super.viewDidLoad()
}
func takePhotoByGalleryOrCamera(){
//MAark Take picture from gallery and camera
//image picker controller to use take image
// uialert controller to make action
let imageController = UIImagePickerController()
imageController.editing = false
imageController.delegate = self;
let alert = UIAlertController(title: "", message: "Profile Image Selctor", preferredStyle: UIAlertControllerStyle.ActionSheet)
let libButton = UIAlertAction(title: "Select photo from library", style: UIAlertActionStyle.Default) { (alert) -> Void in
imageController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imageController, animated: true, completion: nil)
}
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
let cameraButton = UIAlertAction(title: "Take a picture", style: UIAlertActionStyle.Default) { (alert) -> Void in
print("Take Photo")
imageController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(imageController, animated: true, completion: nil)
}
alert.addAction(cameraButton)
} else {
print("Camera not available")
}
let cancelButton = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (alert) -> Void in
print("Cancel Pressed")
}
alert.addAction(libButton)
alert.addAction(cancelButton)
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
alert.modalPresentationStyle = UIModalPresentationStyle.Popover;
// alert.transitioningDelegate = self;
alert.popoverPresentationController!.sourceView = self.view;
alert.popoverPresentationController!.sourceRect = CGRectMake(0, SizeUtil.screenHeight(), SizeUtil.screenWidth(), SizeUtil.screenHeight()*0.4)
alert.popoverPresentationController!.delegate = self;
self.presentViewController(alert, animated: true, completion: nil)
} else {
self.presentViewController(alert, animated: true, completion: nil)
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.Popover
}
//image picker Delegate
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.dismissViewControllerAnimated(true, completion: nil)
let header = profileTableView.headerViewForSection(0) as! ProfileHeaderView
header.btnImage.setImage(image, forState: UIControlState.Normal)
_userProfileImage = image
}
}