iOS Write Data to file, FILE DOES NOT EXIST - ios

I'm tryin to write the datas of an Image in the cacheDirectory, like this :
let imageData = UIImageJPEGRepresentation(image, 1.0) else { fatalError("Impossible to read the image") }
try! imageData.write(to: cachedImageURL, options: .atomic)
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))
Where image is a working UIImage.
the Print statement always returns False. The file is never written, and any exception is raised due to the "try!"
Any idea ?
printing the cachedImageURL, it looks like this
file:///var/mobile/Containers/Data/Application/7B6B72C8-E794-4474-A658-48B66AEA31EC/Library/Caches/79d0e60e-5961-4538-bd9f-28187f4e26d0.jpg

Just figured out. The problem come from my print
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))
which should be cachedImageURL.path insteadOf cachedImageURL.absoluteString
print(fileManager.fileExists(atPath: cachedImageURL.path))

You can Try below Code for saving Images to Caches Directory
*NOTE : if you are saving more than one, please give different image name for all
let fileManager = FileManager.default
let imageName = "image.jpg" //Need to change if more images want to save
do {
let cachesDirectory = try fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = cachesDirectory.appendingPathComponent(imageName)
let image = your image //Give your image here
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
try imageData.write(to: fileURL)
print("Image Saved")
}
} catch {
print(error.localizedDescription)
}

Related

Can not get proper firebase image save in document directory in swift 4 iOS

i'm saving firebase image in document directory !! For uniqueness my Document Directory name is firebase image name ! i have check with a condition that if firebase image name is not exists in my document directory then save that image in Document Directory !!
i'm checking if that firebase name means it save in document directory then it get document directory image if not then it get image from Firebase !!
Issue is when i try to get image :-
(1) For example :- Firebase Image name is 1.jpg .
(2) Document Directory save image with firebase name like 1.jpg .
(3) now i change firebase image to other but it save with name 1.jpg .
(4) when i try to get image because already 1.jpg is in Document Directory that's why it not return me updated image it show me previous 1.jpg image !!
how can i solved this issue. Thank You
Save And Get Image Code :-
func saveImageDocumentDirectory(imageName: String){
let documentPath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let imgURL = documentPath.appendingPathComponent(imageName, isDirectory: true)
if !FileManager.default.fileExists(atPath: imgURL.path){
do{
let image = UIImage(named: imgURL.path)
try image?.pngData()?.write(to: imgURL)
}catch let err{
print("error in save:\(err.localizedDescription)")
}
}
}
func getDocumentImage(imageName: String, firebaseImgURL: URL, imgView:UIImageView){
let documentPath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let imgURL = documentPath.appendingPathComponent(imageName, isDirectory: true)
let image = UIImage(contentsOfFile: imgURL.path)
if image != nil{
imgView.image = image
}else{
imgView.kf.setImage(with: firebaseImgURL)
}
}
Please try with like below code
Save Data
let placeholderURL: URL =
getDocumentDirectoryPath()!.appendingPathComponent("\(imageName.JPG)/",
isDirectory: true)
let fileExists: Bool = FileManager.default.fileExists(atPath: placeholderURL.path )
if !fileExists {
let thumbnailImageURL = URL(string: firebaseURL)
var placeholderData: Data? = nil
if let url = url {
do {
placeholderData = try Data(contentsOf: (thumbnailImageURL ?? nil)!)
} catch {
print("Unable to load data: \(error)")
}
}
if urlData != nil {
do {
//saving is done on main thread
try placeholderData?.write(to: URL(fileURLWithPath: placeholderURL.path) , options: .atomic)
} catch {
print(error)
}
}
}
Retrive image
let thumbnailURL: URL = getDocumentDirectoryPath()!.appendingPathComponent("\("imageName.JPG")/", isDirectory: true)
let fileExists: Bool = FileManager.default.fileExists(atPath: thumbnailURL.path)
var urlThumbnail:URL? = nil
if fileExists {
urlThumbnail = URL(fileURLWithPath: thumbnailURL.path)
} else {
urlThumbnail = URL(string: firebaseURL)
}
Sat image in image view
self.imgtemp.sd_setImage(with: urlThumbnail, placeholderImage: UIImage(named: "placeholder.png"))

How do I change the value stored in a image file in swift 4

I save my first image and it loads, but when I save the second, the image of the button stays the same as the first image I saved. Can someone show me how to have that files value be able to change?
Here is the code that runs when someone picks an image:
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// choose a name for your image
let fileName = "image.jpg"
// create the destination file url to save your image
let fileURL = documentsDirectory.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
if let data = UIImageJPEGRepresentation(pickedImage, 1.0),
!FileManager.default.fileExists(atPath: fileURL.path) {
do {
// writes the image data to disk
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
if let image = getSavedImage(named: "image.jpg") { Button1.setImage(image, for: .normal)
}
And here is my code for when the view loads:
if let image = getSavedImage(named: "image.jpg") {
Button1.setImage(image, for: .normal)
}
As #rmaddy mentioned you already saved image thats why image not replaced. but if you want on tap of button image will be change you need to do some extra work, you need to check if image.jpg exist then add new image with diff name.To check image exist use this method, This method return bool value and path of the file if file exist.So on these two values you can remove your existing image or create new image with different name, according to your code behaviour.
static func isFileExit(filename: String) -> (fileExist: Bool? , path: URL?) {
if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
let filepath = URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(filename)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filepath.path) {
print("FILEAVAILABLE")
return (true, filepath)
}
}
return (false,nil)
}
You're saving your images only if the image doesn't exist, so when you try to save the second image, its not being saved because the first image already exists.
//you should double check what you're doing here
if let data = UIImageJPEGRepresentation(pickedImage, 1.0),
!FileManager.default.fileExists(atPath: fileURL.path) {
do {
// writes the image data to disk
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}

Image in document directory is not changing after overwriting

I need to upload image in local and to get it later. Now my problem is I can store and get the correct image while I am trying at very first time after launching the app. But when I try to upload the same file with same name but with different image, I am getting the previously stored image.
Here's my code:
let i = "image1"
let str = String(i).appending(".png")
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(str)
if fileManager.fileExists(atPath: paths) {
do {
try fileManager.removeItem(atPath: paths)
print("old image has been removed")
} catch {
print("an error during a removing")
}
}
let imageData = UIImageJPEGRepresentation(uploadingImage!, 0.5)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
and I am getting the URL as String like,
let myImagePath = URL(fileURLWithPath: paths)
Someone please help me to find the problem in my code...
try use
imageData?.write(to: URL(fileURLWithPath: paths))
instead of
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
I do not see why your code should not work. However, the required workflow to safely replace a file is:
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(atPath: path)
} catch let error {
print("Cannot delete file on device: \(path): \(error)")
return
}
}
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)

UIImageJPEGRepresentation | generateJPEGRepresentation saves image as nil? Swift 3

I am currently designing a database management application with Realm, where I have managed to create and retrieve an object successfully. The problem I am having is with updating/editing - specifically updating the UIImage that the user has uploaded. With Realm, I save the path of the image and then retrieve it by loading that path (in Documents Directory).
When the user tries to save the changed image, for some odd reason the UIImageJPEGRepresentation saves the changed image as nil, thus removing the user's image. It's strange because the initial creation of a data object stores it just fine.
I have tried to check whether the image is being passed correctly with some debugging, and have found that it does so just fine and the right path is being saved on.
Here is my update method:
func updateImage() {
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("\(selectedPicPath!)")
if FileManager.default.fileExists(atPath: fileURL.path) {
do {
if profilePic.image != nil {
let image = profilePic.image!.generateJPEGRepresentation()
try! image.write(to: fileURL, options: .atomicWrite)
}
} catch {
print(error)
}
} else {
print("Image Not Added")
}
}
Can anyone see any problems?
let image = profilePic.image!.generateJPEGRepresentation()
Check this line, whether it is returning nil value or data? If nil, then use following code to test your image store, it's working. Also ensure your actual image has JPEG file format extension, that you are trying to generate.
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
// For PNG Image
if let image = UIImage(named: "example.png") {
if let data = UIImagePNGRepresentation() {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
For JPG image
if let image = UIImage(named: "example.jpg") {
if let data = UIImageJPEGRepresentation(image, 1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.jpg")
try? data.write(to: filename)
}
}

Swift 3.0 writing Image to Directory

I have a simple ImagePicker for the user to select, or take, a profile picture. I want to save this image to the Home Directory for easy loading later.
The problem is with the Image type not being set.
//Save Image
_ = PPimagePicked.image
let imageData = UIImageJPEGRepresentation(PPimagePicked.image!, 0.6)
let compressedJPGImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)
// Get Document Root Path
let path = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/profile.jpg")
do {
//Save image to Root
try imageData?.write(to: path, options: .atomic)
print("Saved To Root")
} catch let error {
print(error)
}
The exact Error is :
"[Generic] Creating an image format with an unknown type is an error"
Please try this code i am using it in swift 2.2. Below method includes for both UIImageJPEGRepresentation, UIImagePNGRepresentation
if let image = UIImage(named: "example.png") {
if let data = UIImageJPEGRepresentation(image, 0.8) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
if let image = UIImage(named: "example.png") {
if let data = UIImagePNGRepresentation(image) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}
try converting the image to image data
let imageCapture = UIImage(data: dataImage)!
UIImageWriteToSavedPhotosAlbum((image: imageCapture), nil, nil, nil)

Resources