Getting URL of UIImage selected from UIImagePickerController
Okay, I've solved the issue.
All you have to do is simply grab the image (info[UIImagePickerControllerOriginalImage] as UIImage
) and save to the given directory. If you need to save only 1 picture it works great. The code id below.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
let imageName = imageURL.path!.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
let localPath = documentDirectory.stringByAppendingPathComponent(imageName)
let image = info[UIImagePickerControllerOriginalImage] as UIImage
let data = UIImagePNGRepresentation(image)
data.writeToFile(localPath, atomically: true)
let imageData = NSData(contentsOfFile: localPath)!
let photoURL = NSURL(fileURLWithPath: localPath)
let imageWithData = UIImage(data: imageData)!
picker.dismissViewControllerAnimated(true, completion: nil)
}
Getting URL of UIImage from UIImagePickerController
Apple has changed something in their NSString
and NSURL
library in their latest release (iOS 9), but those methods are available from iOS 4. You can check the related Apple Forum Post for more details.
For fixing this error, you need to change the code like:
Swift 2:
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!)
{
let imageUrl = editingInfo[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.URLByAppendingPathComponent(imageName!)
let image = editingInfo[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
data!.writeToFile(localPath.absoluteString, atomically: true)
self.dismissViewControllerAnimated(true, completion: nil);
}
Swift 3:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
self.dismiss(animated: true, completion: nil);
}
Reference:
- lastPathComponent
- URLByAppendingPathComponent:
Get Image URL of photo with UIImagePickerControllerDelegate
Yes, but with another key:
info[UIImagePickerController.InfoKey.originalImage] as? UIImage
or
info[UIImagePickerController.InfoKey.editedImage] as? UIImage
Please note that the object there will be UIImage type, not URL
Camera photos are not saved by default and don't have local path. So you need to save it by yourself. E.g.:
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
try? image.pngData()?.write( .... )
}
How to get the URL of a chosen photo in users library or camera?
You are not building your path correctly. There are a few issues:
You are just appending the file name to the pictures path string. You’re missing a slash between the folder and the file name. Obviously, you can add this yourself, but for future reference, if you work with URLs, it would have added the necessary slash for you.
This “pictures” directory is not for iOS. I’d suggest a different folder. Perhaps copy this to a folder in the temporary directory, upload from there, and then clean up when you’re done.
If you’re wondering why your code worked on the simulator, but not the device, it’s because the former doesn’t enforce sandbox rules, whereas the latter will.
As an aside, I’d suggest avoiding “round tripping” through a UIImage
unless necessary. Above, we’re dealing with the raw asset, but if you create a UIImage
, only to then extract the JPG or PNG representation, you’ll lose information about your asset, and likely make the asset bigger than it needs to be. It’s far more efficient to just grab the image URL, copy that file, and upload:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let imageUrl = info[.imageURL] as? URL else {
return
}
do {
let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("uploads")
try FileManager.default.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil)
let fileURL = tempDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathComponent(imageUrl.pathExtension)
try FileManager.default.copyItem(at: imageUrl, to: fileURL)
// when done, clean up (presumably in the completion handler of the async upload routine)
try FileManager.default.removeItem(at: fileURL)
} catch {
print(error)
}
dismiss(animated: true)
}
How to get URL from UIImage?
CKAsset
represents some external file (image, video, binary data and etc). This is why it requires URL
as init parameter.
In your case I would recommend to use following steps to upload large image to CloudKit:
- Save
UIImage
to local storage (e.g. documents directory). - Initialize
CKAsset
with path to image in local storage. - Upload asset to Cloud.
- Delete image from local storage when uploading completed.
Here is some code:
// Save image.
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let filePath = "\(path)/MyImageName.jpg"
UIImageJPEGRepresentation(image, 1)!.writeToFile(filePath, atomically: true)
let asset = CKAsset(fileURL: NSURL(fileURLWithPath: filePath)!)
// Upload asset here.
// Delete image.
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
print(error)
}
Related Topics
How to Debug "Invalid Bundle" Error Which Happens Only After Submitting to App Store
How to Hide/Show Tabbar When Tapped Using Swift in iOS8
Ios: Place Uiview on Top of Uitableview in Fixed Position
Watch Os 2.0 Beta: Access Heart Beat Rate
How to Change the Size of Uiactivityindicator
Uitextview Starts at Bottom or Middle of the Text
How to Generate an iOS IPA File with Ionic Framework
Open Specific View When Opening App from Notification
Disabled Uibutton Not Faded or Grey
How to Apply a Tintcolor to a Uiimage
Uirefreshcontrol - Pull to Refresh in iOS 7
Export Compliance in iOS App Submission
Create Uicollectionviewcell Subclass with Xib
Swiftui Datepicker Jumps Between Short and Medium Date Formats When Changing the Date
Swift If Statement - Multiple Conditions Separated by Commas
Apns Notifications Not Reaching Devices Enrolled in Apple Mdm