Get Image from Documents Directory Swift

Get image from documents directory swift

You are finding the document directory path at runtime for writing the image, for reading it back, you can use the exact logic:

Swift 3 and Swift 4.2

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("Image2.png")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}

Swift 2

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
if paths.count > 0
{
if let dirPath = paths[0] as? String
{
let readPath = dirPath.stringByAppendingPathComponent("Image2.png")
let image = UIImage(contentsOfFile: readPath)
// Do whatever you want with the image
}
}
}

Get images from Document Directory not file path Swift 3

It's simply because your image's name is invalid. Use the debugger to find the exact value of imageUrl, I bet it's something like this .../Documents/img. What you want is more like .../Documents/Sep-04-2017-12.img

You'd have to store currentFileName in the view controller so you can reference it later.

Also, your naming strategy is pretty fragile. Many images can end up sharing one name.


If you have a folder full of images, you can iterate on that folder to get back the img files:

let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)
for imageURL in directoryContents where imageURL.pathExtension == "img" {
if let image = UIImage(contentsOfFile; imageURL.path) {
// now do something with your image
} else {
fatalError("Can't create image from file \(imageURL)")
}
}

How to retrieve saved UIImageViews from documents folder in Swift?

You can retrieve it like this

func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage? {

let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
if let image = UIImage(contentsOfFile: imageURL.path) {
return image

} else {
print("image not found")

return nil
}
}
return nil
}

And for saving

func saveImageToDocumentDirectory(image: UIImage , imageName: String) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = imageName // name of the image to be saved
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = image.jpegData(compressionQuality: 1),
!FileManager.default.fileExists(atPath: fileURL.path){
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}

How do I get list of Images saved in a folder?

The same way you're appending directoryName when composing your fileURL, you can get directoryURL and read its files:

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryURL = documentsURL.appendingPathComponent(directoryName)
do {
let fileURLs = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil)
// process files
} catch {
print(error)
}

How to display an image from documents directory to UIImageView in Swift 3?

Apple is trying to move everyone off the path-as-string paradigm to URL (i.e. file:///path/to/file.text). The Swift API pretty much removes all path in favor of URL.

You can still find it in Objective-C (NSString):

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let getImagePath = NSString.path(withComponents: [paths, "fileName"])

The more Swifty way:

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: paths).appendingPathComponent("fileName")

Swift 3 adding an Image to Documents and Retrieving

Well after a few hours I figured it out. Looks like the directory wasn't being created. Solved it by:

func saveImageDocumentDirectory(image: UIImage){
if let userUID = Auth.auth().currentUser?.uid{
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")

do {
try UIImagePNGRepresentation(image)?.write(to: fileURL, options: .atomic)
} catch {
print(error)
}
}
}

func getImage() -> UIImage{
if let userUID = Auth.auth().currentUser?.uid{
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("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")
if let image = UIImage(contentsOfFile: imageURL.path){
return image
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}

}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}

Save and get image from folder inside Documents folder on iOS wrong path

You can initialize your path variables as global variables at the top of your class, then just modify them within your requestImage method.

Then when you want to retrieve those images, you can just use the same variable name to ensure that it is the exact same path.

EDIT*
I think you may need to be reading some NSData instead. You can use UIImagePNGRepresentation or UIImageJPEGRepresentation to write your file to the documents directory. I found a tutorial here



Related Topics



Leave a reply



Submit