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)")
}
}
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
}
}
}
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")
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
Loading downloaded images in Documents directory (IOS 10, xcode 8.1, Swift 3.0)
So what I did to fix the problem is to transfer the webviews directory to the /Libraries directory and store the photos I downloaded to /Libraries/Caches
let functionName:String = "moveFileToLibrary"
let library = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
let bundle = Bundle.main.path(forResource: "webviews", ofType: "")!
let fileManager = FileManager.default
if fileManager.isWritableFile(atPath: library.path)
{
if self.debug {print("\(functionName) @ \(self.className) => \(library.path) : File is writable")}
}
else
{
if self.debug {print("\(functionName) @ \(self.className) => \(library.path) : File is read-only")}
}
if fileManager.isWritableFile(atPath: bundle)
{
if self.debug {print("\(functionName) @ \(self.className) => \(bundle) : File is writable")}
}
else
{
if self.debug {print("\(functionName) @ \(self.className) => \(bundle) : File is read-only")}
}
if !fileManager.fileExists(atPath: library.appendingPathComponent("webviews").path)
{
do
{
try fileManager.copyItem(atPath: bundle, toPath: library.appendingPathComponent("webviews").path)
if self.debug {print("\(functionName) @ \(self.className) => Webviews folder copied!")}
}
catch let error
{
if self.debug {print("\(functionName) @ \(self.className) => Error Writing Webviews folder: \(error.localizedDescription)")}
}
}
else
{
if self.debug {print("\(functionName) @ \(self.className) => Webviews folder exists. Continue woth life.")}
}
Related Topics
Swift Generic Protocol Function Parameters
Swift: Casting a Floatingpoint Conforming Value to Double
Calling a Child Inside 2 Levels of Nodes
What Does This Mean? Variable Declared Followed by a Block Without Assignment
Swift 3:Delegate Within Tapgesturerecognizer in Generics Doesn't Get Called
Swiftui - Navigation View Opening with Back Button and Half Grey Screen/Weird Behavior
Swift: Call Self Method Inside Init
Deleterowsatindexpaths Crashing
Nsurl from String Gets Truncated, Dots on the Uivideoeditorcontroller's Video Path Swift 2 iOS 8
How to Have Either or Wherefields for Firestore Query
C++ Dylib in Swift Project - Undefined Symbols for Function Exposed in Dylib
Use Huge Numbers in Apple Swift
Swiftui How to Programatically Adjust Spacing Between Images and Text
How to Loop All Firebase Children at Once in the Same Loop
Autoscrolling Infinite Effect in .Linear Type of Icarousel in Swift
Can Openssl Be Bundled for Wget Wrapper App to Reference in Xcode Project
Why Does Classa Adopting Protocolb Not Satisfy the Protocolb Requirement
Swift Enum with Custom Initializer Loses Rawvalue Initializer