File Directory Changing Every Reboot Swift iOS - swift

I am currently saving images a user selects from their photo library & saving the url to User Defaults.
The issue I am currently facing is whenever my app reboots, such as an Xcode re-launch the URL I am saving to User Defaults is no longer valid. From my understanding/researching I need to save a relative URL for the image; however I am not having any luck doing this correctly. This occurs with both simulator & actual device.
From my UIImagePicker here are my steps:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.originalImage] as? UIImage else { return }
let savingImage : SavingImage = SavingImage()
let ourStringedUrl : String = savingImage.saveImageDocumentDirectory(image: image, imageName: image.description)
}
From SavingImage, here is the saving of the photo itself
func getDirectoryPath() -> NSURL {
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("AllImages")
let url = NSURL(string: path)
return url!
}
func saveImageDocumentDirectory(image: UIImage, imageName: String) -> String {
let fileManager = FileManager.default
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("AllImages")
if !fileManager.fileExists(atPath: path) {
try! fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
let url = NSURL(string: path)
let imagePath = url!.appendingPathComponent(imageName)
let urlString: String = imagePath!.absoluteString
let imageData = image.jpegData(compressionQuality: 1)
fileManager.createFile(atPath: urlString as String, contents: imageData, attributes: nil)
return urlString as String
}
& Finally here is how I am loading the image itself:
func getImageFromDocumentDirectory(imageName : String) -> UIImage {
let fileManager = FileManager.default
var ourImage : UIImage!
let imagePath = "\(imageName)"
let urlString: String = imagePath
if fileManager.fileExists(atPath: urlString) {
ourImage = UIImage(contentsOfFile: urlString)
} else {
if ourImage == nil {
ourImage = UIImage(named: "defaultImage.png")
}
}
return ourImage
}
Where am I going wrong with the loading aspect? How exactly should I be saving the URL?
The URL that is being saved looks something similar to the following:
//var/mobile/Containers/Data/Application/17C16D0D-1BFA-44F5-A6BD-18DFAEA051E0/Documents/AllImages/%3CUIImage:0x280a393b0%20anonymous%20%7B3024,%204032%7D%3E
But will come up as nil upon loading the image on reboot.

The new directory will be created every time you reboot your simulator or every time you install new build to device. (Uninstall previous and install new). iOS does not give us permission to select the directory. As you install new application it will create its sandbox. Please make sure you check your directory on the same build.

An alternative might be to use iCloud Drive and upload your image there. The iCloud drive is linked to an user's iCloud account, and therefore should persist in case of an app update.
Here's a great tutorial to get started: https://theswiftdev.com/2018/05/17/how-to-use-icloud-drive-documents/
Here's a link to the docs: https://developer.apple.com/icloud/icloud-drive/

Related

'Cannot subscript a value of type '[NSObject : AnyObject]' with an index of type 'UIImagePickerController.Infokey'

I'm work on a app which will be able to send mail without using IOS's client.
I deciced to use the mailcore2 async api.
For now I'm able to send an email but i'd like to add attachment to it and I'm actually trying to on the click of a button, open the gallery, select a picture and get its path.
I'm trying this piece of code but an error appears at line 2 and 7 with my "
let imageURL
and
let image
":
"Cannot subscript a value of type '[NSObject : AnyObject]' with an
index of type 'UIImagePickerController.InfoKey'
Here is the code :
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let imageURL = info[UIImagePickerController.InfoKey.referenceURL] as NSURL
let imageName = imageURL.path!.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first as! String
let localPath = documentDirectory.stringByAppendingPathComponent(imageName)
let image = info[UIImagePickerController.InfoKey.originalImage] 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.dismiss(animated: true, completion: nil)
}
You’re using an older version of Swift, to get the image URL:
let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
I suggest that you upgrade to Swift 5.0 in the future

swift image picker gets several pictures

i have a problem with inserting images into a CollectionView cell using an ImagePicker. The problem is, if I click on a photo which I would like to insert quickly several times, then the photo is inserted several times in different cells.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
picker.allowsEditing = true
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
collectionViewController?.imageArray.append(pickedImage)
collectionViewController?.newImages.append(pickedImage)
let guid = UUID()
let fileManager = FileManager.default
let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("\(guid).png")
let data = UIImagePNGRepresentation(fixOrientation(img: pickedImage))
fileManager.createFile(atPath: imagePath as String, contents: data, attributes: nil)
let image = CoreDataManager.shared.createImageyObject(pfad: imagePath, date: Date(), guid: guid)
collectionViewController?.images.append(image)
if collectionViewController?.images.count == 1 {
collectionViewController?.images[0].isBaseImage = true
collectionViewController?.lastIndex = 0
}
collectionViewController?.update()
}
}
Mediainfo contains image url, media url... Maybe you should cache picked imageURL (that unique) in a Set then check if imageURL that's already existed.

Unable to save images in the right directory

I am trying to save images in a directory. Images are correctly saved in the right place, but when I inspect these with the path in the finder, all the images are damaged and unsable.
damaged images
Below the static method:
static func writeImageFile(with data: Data, issue: Issue, page: Int, isThumbnail: Bool) throws -> URL {
let url = MediaFileManager.issueImagesDirectoryURL(issue: issue).ensuringDirectoryExists()
let imageURL = url.appendingPathComponent(imageName(for: page, isThumbnail: isThumbnail))
try data.write(to: imageURL)
return url
}
And the call in the class:
DispatchQueue.main.async {
guard let data = result.data else {
self.downloadDidFail(for: result.page)
return
}
do {
let writeImageFile = try MediaFileManager.writeImageFile(with: data, issue: self.issue, page: result.page, isThumbnail: false)
let writeThumbFile = try MediaFileManager.writeImageFile(with: data, issue: self.issue, page: result.page, isThumbnail: true)
print(writeImageFile)
print(writeThumbFile)
} catch let error as NSError {
print(error.localizedDescription)
}
}
I will assume, since you don't quite specify this, that you have a bunch of UIImage objects.
And I also noticed that you want your images to be saved as JPEG, which is no trouble at all, don't worry.
I would go with something like this:
if let image = UIImage(named: "example.png") {
if let data = UIImageJPEGRepresentation(image, 1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
Where the func getDocumentsDirectory() is the following:
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
You might wonder why I used 1.0 for the second parameter in UIImageJPEGRepresentation, well that's the JPEG quality mapped between 0.0 and 1.0 (it's a float).
If you have any details that I am not aware of, please reply and I will try to help accordingly.
Hope it helps you, cheers!
Source: link
Have you tried to load the image to a UIImageView to see if the images are being properly downloaded? imageView.image = UIImage(data: data).
But I also detect that you're saving Data instead of the image, in order to make sure that you're saving an image I would try the following
static func writeImageFile(with data: Data, issue: Issue, page: Int, isThumbnail: Bool) throws -> URL {
let url = MediaFileManager.issueImagesDirectoryURL(issue: issue).ensuringDirectoryExists()
let imageURL = url.appendingPathComponent(imageName(for: page, isThumbnail: isThumbnail))
let image = UIImage(data: data)
let imgData = UIImageJPEGRepresentation(image, 1)
try imgData.write(to: imageURL)
return url
}
Yes, it might have unnecessary steps, worth trying, this way we're making sure that it's saved as Jpeg. But again, I would check if the images are being properly downloaded first.

Save image in Realm

I'm trying to pick image from device's Photo Library in method:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
userPhoto.image = info[UIImagePickerControllerOriginalImage] as! UIImage?
userPhoto.contentMode = .scaleAspectFill
userPhoto.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
and save this picture in Realm (as NSData):
asset.assetImage = UIImagePNGRepresentation(userPhoto.image!)! as NSData?
...
try! myRealm.write
{
user.assetsList.append(asset)
myRealm.add(user)
}
After build succeeded and trying to pick and save image (in the app) i have app error:
'Binary too big'
What i'm doing wrong?
P.S. Sorry for my English :)
After some actions i have this code. But it's overwrite my image.
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
}
userPhoto.image = image
userPhoto.contentMode = .scaleAspectFill
userPhoto.clipsToBounds = true
urlCatch = (localPath?.path)!
self.dismiss(animated: true, completion: nil);
}
Don't save the image itself into realm, just save the location of the image into realm as String or NSString and load the image from that saved path. Performance wise it's always better to load images from that physical location and your database doesn't get too big
func loadImageFromPath(_ path: NSString) -> UIImage? {
let image = UIImage(contentsOfFile: path as String)
if image == nil {
return UIImage()
} else{
return image
}
}
or you just save the image name, if it's in your documents directory anyhow
func loadImageFromName(_ imgName: String) -> UIImage? {
guard imgName.characters.count > 0 else {
print("ERROR: No image name")
return UIImage()
}
let imgPath = Utils.getDocumentsDirectory().appendingPathComponent(imgName)
let image = ImageUtils.loadImageFromPath(imgPath as NSString)
return image
}
and here a rough example how to save a captured image to your directory with a unique name:
#IBAction func capture(_ sender: AnyObject) {
let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (imageDataSampleBuffer, error) -> Void in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
//self.stillImage = UIImage(data: imageData!)
//self.savedImage.image = self.stillImage
let timestampFilename = String(Int(Date().timeIntervalSince1970)) + "someName.png"
let filenamePath = URL(fileReferenceLiteralResourceName: getDocumentsDirectory().appendingPathComponent(timestampFilename))
let imgData = try! imageData?.write(to: filenamePath, options: [])
})
/* helper get Document Directory */
class func getDocumentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
//print("Path: \(documentsDirectory)")
return documentsDirectory as NSString
}
https://realm.io/docs/objc/latest/#current-limitations
maximum data size is 16 MB . this is limitation of realm
Depending on how your serializing the image data (for example if it's a lossless bitmap), it's quite possible that this data exceed 16MB, which as you've stated is Realm's maximum supported size for binary properties.
When you invoke NSData.length, how large does it say your data is?

Issue setting UIImageView from local image in documents directory

I am trying to load images that I have downloaded using Alamofire to the documents directory. I store the filenames in a Realm database. Once it is time to display the image I take the path to the documents directory and append the filename. This path doesn't seem to work for building a UIImage though.
if let name = playlist.RLMsongs[indexPath.row].name, let imageURL = playlist.RLMsongs[indexPath.row].album?.image?.getImageURL(.SmallImage), let fileName = playlist.RLMsongs[indexPath.row].album?.image?.smallLocalFileName {
cell.songName.text = name
let range = imageURL.rangeOfString("http")
if let theRange = range where theRange.startIndex == imageURL.startIndex { // imageURL starts with "http" (remote url)
cell.albumImage.sd_setImageWithURL(NSURL(string: imageURL), placeholderImage: UIColor.imageFromColor(UIColor.grayColor())) {
_ in
cell.albumImage.fadeIn(completion: nil)
}
} else {
cell.albumImage.image = UIImage(named: fileName) // images still do not load
// tried this first -> cell.albumImage.sd_setImageWithURL(NSURL(fileURLWithPath: imageURL), placeholderImage: UIColor.imageFromColor(UIColor.grayColor()))
}
}
Here is the bit that builds the path (imageURL above):
let documentsDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let path = documentsDir.URLByAppendingPathComponent(localFile).path
return path
As per TiM's recommendation I checked the value of imageURL on a breakpoint and it looks just fine:
imageURL: "/Users/danielnall/Library/Developer/CoreSimulator/Devices/0B8D64B5-9593-4F86-BBD3-E408682C5C0F/data/Containers/Data/Application/011E4805-40EB-4221-9D7D-1C1D64660186/Documents/75.9226ecd6893cb01a306c974d9d8ffd62803109c1.png"
This is the full path on the simulator and is only missing the file schema (file://) which for the use of NSURL fileURLWithPath should be just fine I think.
If you already have the PNG file in Documents then all you need to do is this.
(Assuming that cell.albumImage is UIImageView)
let imageFileName = "75.9226ecd6893cb01a306c974d9d8ffd62803109c1.png"
cell.albumImage.image = UIImage(named: imageFileName)
Check if file exists:
func fileExists(filePath: String) -> Bool {
let filemanager = NSFileManager.defaultManager()
if filemanager.fileExistsAtPath(filePath) {
return true
}
return false
}
I ended up finding the solution to the problem which was unrelated to the direction of this question. Turned out that the issue was in my override of the prepareForReuse method in my UITableViewCell class. Thank you for everyone's suggestions though.