How to extract image filename from UIImage - swift

I have <UIImage: 0x6040000b9800> , {1668, 2500} name for taken photo from gallery. But I need imagename in String. Anyone help me to solve in swift 4? I have given codes below:
extension PhotoViewController: ImagePickerDelegate {
func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
}
func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
self.image = images[0]
let navigati:PhotoDescriptorController = storyboard!.instantiateViewController(withIdentifier: StoryBoard.PhotoDescriptorController) as! PhotoDescriptorController
navigati.imageDest = self.image
self.navigationController?.pushViewController(navigati, animated: true)
imagePicker.dismiss(animated: true, completion: nil)
}
func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
imagePicker.dismiss(animated: true, completion: nil)
}

Have you tried using Photo framework to get imageName?
See this example.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
let assetResources = PHAssetResource.assetResources(for: asset)
print(assetResources.first!.originalFilename)
}
dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let picURL = info[UIImagePickerControllerReferenceURL] as? URL {
let imgData = PHAsset.fetchAssets(withALAssetURLs: [picURL], options: nil)
let asset = imgData.firstObject
print(asset?.value(forKey: "filename"))
}
dismiss(animated: true, completion: nil)
}

Related

How to get filename when using PHPickerViewController for photo

How to get filename when using PHPickerViewController for photo
this is my function code
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
dismiss(animated: true, completion: nil)
for item in results {
item.itemProvider.loadObject(ofClass: UIImage.self) {(image, error) in
if let image = image as? UIImage{
}
}
}
}
Please help, thank you
Hope you van find file name by using this:
item.itemProvider.loadFileRepresentation(forTypeIdentifier: "public.item") { (url, error) in
if error != nil {
print("error \(error!)");
} else {
if let url = url {
let filename = url.lastPathComponent;
print(filename)
}
}
}
You can use this to get file name from UIImagePickerController
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
let asset = result.firstObject
print(asset?.value(forKey: "filename"))
}
dismiss(animated: true, completion: nil)
}
The NSItemProvider from PHPickerResult has a suggestedName property that will give you the file name. So from your provided code:
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
dismiss(animated: true, completion: nil)
for item in results {
item.itemProvider.loadObject(ofClass: UIImage.self) {(image, error) in
// This will give you the file name
guard let fileName = item.itemProvider.suggestedName else { return }
if let image = image as? UIImage{
}
}
}
}

Firebase storage

I tried to upload images into firebase storage, and fyi my app is under firebase phone number Auth registration. And here is my code for uploading images:
#IBAction func addBtnClicked(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
selectedImageFromPicker = editedImage
} else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
imageView.image = selectedImage
}
let storageRef = Storage.storage().reference().child("profile_images").child("test01.png")
if let uploadData = UIImagePNGRepresentation(self.imageView.image!) {
storageRef.putData(uploadData, metadata: nil) { (metadata, error) in
if let error = error {
print(error)
return
}
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("canceled picker")
dismiss(animated: true, completion: nil)
}
But every time after I compiled, I got this error code:
User does not have permission to access gs://cal-dev.appspot.com/profile_images/test01.png." UserInfo={object=profile_images/test01.png, ResponseBody={
"error": {
"code": 403,
"message": "Permission denied. Could not perform this operation"
}
Have you given read and write access in your firebase console? It seems that you are not authorized to write data to firebase..

How can I make this imagePickerController able to accept edited images?

How can I make this imagePickerController able to accept edited images?
When selecting an image and adjusting it (zoom in and out) and selecting done, the image reverts back to its original state. What can I add to to my code to have the zoomed image save and show up in my image view?
The following is my code so far:
let cameraRollAction = UIAlertAction(title: "Camera Roll", style: .default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.mediaTypes = [kUTTypeImage as String]
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(picker, animated: true, completion: nil)
self.newPic = false
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as String) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profileImageView.image = selectedImage
if newPic == true {
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(imageError), nil)
}
}
self.dismiss(animated: true, completion: nil)
}
Instead of
UIImagePickerControllerOriginalImage
use
UIImagePickerControllerEditedImage
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as String) {
let selectedImage = info[UIImagePickerControllerEditedImage] as! UIImage ?? info[UIImagePickerControllerOriginalImage] as! UIImage // will return original image if edited image is not available
profileImageView.image = selectedImage
if newPic == true {
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(imageError), nil)
}
}
self.dismiss(animated: true, completion: nil)
}

Allow the user to choose the profile picture he wants and change whenever he wants

I need help please i try to do UIImage without a picture for the user can choose a picture he wants! And it's important that the user-selected image holds the same once the user is completely signed out of the app
And he can change it whenever he wants to see what picture he wants
displayed on the profile picture (UIImage)
Swift 4
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var imageView: UIImageView!
#IBOutlet var chooseBuuton: UIButton!
var imagePicker = UIImagePickerController()
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
self.dismiss(animated: true, completion: { () -> Void in
})
imageView.image = image
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
imageView.contentMode = .scaleAspectFill
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)
}
}
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

Getting location details from image in ios swift

I am trying to get location details from image using
UIImagePickerControllerReferenceURL but I found that PHAsset.fetchAssets(withALAssetURLs: [URL], options: opts) has been deprecated .Please help me in getting location details.
Can we do it using PHAssetCollection?. If so please help me
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
print(info)
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
selectedImage.contentMode = .scaleAspectFit
selectedImage.image = chosenImage
dismiss(animated:true, completion: nil)
if let URL = info[UIImagePickerControllerReferenceURL] as? URL {
let opts = PHFetchOptions()
opts.fetchLimit = 1
let assets = PHAsset.fetchAssets(withALAssetURLs: [URL], options: opts)
let asset = assets[0]
print(asset.location)
// The location is "asset.location", as a CLLocation
// ... Other stuff like dismiss omitted
}
}
Only solution I found so far is to use the iOS 10 code block even in iOS 11 and just ignore the UIImagePickerControllerReferenceURL deprecated message (the key still exists and works in iOS 11)
import AssetsLibrary
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL{
print(imageUrl.absoluteString) //"assets-library://asset/asset.JPG?id=ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED&ext=JPG"
// access image from URL
let assetLibrary = ALAssetsLibrary()
assetLibrary.asset(for: imageUrl as URL! , resultBlock: { (asset: ALAsset!) -> Void in
if let actualAsset = asset as ALAsset? {
let assetRep: ALAssetRepresentation = actualAsset.defaultRepresentation()
let iref = assetRep.fullResolutionImage().takeUnretainedValue()
let image = UIImage.init(cgImage: iref)
self.img.image = image
}
}, failureBlock: { (error) -> Void in
})
}
dismiss(animated: true, completion: nil)
}
Hope this will help.