Get images from Document Directory not file path Swift 3 - swift

This is how I saved the images
let format = DateFormatter()
format.dateFormat="MMMM-dd-yyyy-ss"
let currentFileName = "\(format.string(from: Date())).img"
print(currentFileName)
// Save Images
let fileMgr = FileManager.default
let dirPath = fileMgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
let imageFileUrl = dirPath.appendingPathComponent(currentFileName)
do {
try UIImagePNGRepresentation(returnedImages)!.write(to: imageFileUrl)
print("Image Added Successfully")
} catch {
print(error)
}
Below is code I am using to retrieve images, But I am getting the URL instead of the image file to populate tableview. Any help would be appreciated
let fileManager = FileManager.default
let imageUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask) [0].appendingPathComponent("img")
print("Your Images:\(imageUrl)")

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)")
}
}

Try using this
func getImage(){
let fileManager = FileManager.default
let imagePAth = (self.getDirectoryPath() as NSString).appendingPathComponent("apple.jpg") // saved image name apple.jpg
if fileManager.fileExists(atPath: imagePAth){
self.lockbackImageview.image = UIImage(contentsOfFile: imagePAth)
}else{
print("No Image")
self.lockbackImageview.image = UIImage.init(named: "1.jpg")
}
}

Related

load glb model in SCNScene swift

I have a .glb file in document folder, how do I get the image and load into scnScene? like how I load a uiimage from document folder
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
is it possible to load .glb in SCNScene?
let scene = SCNScene(named: "latest.glb")
answering my own question, I used GLTFSceneKit
let path = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)[0]
.appendingPathComponent("test.glb")
var scene: SCNScene
do {
let sceneSource = try GLTFSceneSource(url: path)
scene = try sceneSource.scene()
} catch {
print("\(error.localizedDescription)")
return
}

How to save images in ascending order in swift?

I am building an application in which i am using FileManager to save some images using device camera. So for Now I am saving file name as Doc-Time.
I am using below code,
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss"
let fileName = "Doc-" + dateFormatter.string(from: Date())
let fileURL = documentsDirectory.appendingPathComponent(fileName
)
if let data = image.jpegData(compressionQuality: 1.0),!FileManager.default.fileExists(atPath: fileURL.path){
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
But Here i want to as, Doc-1,Doc-2, Doc-3....
How can i do that?
You can achieve this by simply storing the next index of the image. Like first the index should be 1 when you used named the image as Doc-1 then the index has 2 in it and so on....
One way to store this index in UserDefaults like:
var nextImageIndex: Int {
UserDefaults.standard.integer(forKey: "NextImageIndex") + 1 //+1 if you want to start with 1
}
func incrementImageIndex() {
UserDefaults.standard.setValue(nextImageIndex, forKey: "NextImageIndex")
}
Put the above code somewhere in UIViewController to see it works.
Here is your updated method...
func saveImageToDocumentDirectory(image: UIImage ) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
let fileName = "Doc-\(nextImageIndex)"
let fileURL = documentsDirectory.appendingPathComponent(fileName)
let fileAlreadyExists = FileManager.default.fileExists(atPath: fileURL.path)
if let data = image.jpegData(compressionQuality: 1.0), !fileAlreadyExists {
do {
try data.write(to: fileURL)
incrementImageIndex()
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
Create a variable to store the document count and increment it every time your save to the document directory, then use that value in the string.
let documentKey = "documentIndex"
#objc var documentIndex: Int {
get { UserDefaults.value(forKey: documentKey) as? Int ?? 0 }
set { UserDefaults.setValue(newValue, forKey: documentKey) }
}
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
documentIndex += 1
let fileName = "Doc-\(documentIndex)"
let fileURL = documentsDirectory.appendingPathComponent(fileName
)
if let data = image.jpegData(compressionQuality: 1.0),!FileManager.default.fileExists(atPath: fileURL.path){
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}

swift how to get all files from a sub folder we created in document directory?

let fileManager = FileManager.default
let documentsFolder = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
do{
let contents = try FileManager.default.contentsOfDirectory(at: documentsFolder,includingPropertiesForKeys: nil,options: [.skipsHiddenFiles])[0]
print(contents)
let directoryContents = try! fileManager.contentsOfDirectory(at: contents, includingPropertiesForKeys: nil)
let item = directoryContents[indexPath.row]
let photoURL = URL.init(fileURLWithPath: item.path)
let data = try? Data(contentsOf: photoURL)
let image = UIImage(data: data!)
cell.imageView.image = image
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
You can manually do this like this :
let fileManager = FileManager.default
let documentsFolder = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let subdirectories = try? fileManager.contentsOfDirectory(atPath: documentsFolder.path)
// this will give the last component only.
for subdirectory in subDirectories {
let photoPath = documentsFolder + “/“ + subdirectory + “/“ + fileManager.contentsOfDirectory(atPath : subdirectory)[indexPath.item]
let photoURL = URL.init(fileURLWithPath: photoPath)
let data = try? Data(contentsOf: photoURL)
let image = UIImage(data: data!)
cell.imageView.image = image
}

How to download a file from URL using Alamofire to a custom folder

I'm using Alamofire to a download file from url, I'm getting filepath, but I'm not able to track down that filepath
let mjString = "https://wallpaperstock.net/wallpapers/thumbs1/42535.jpg"
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("destinationURLForFile *********** \(documentsURL)")
let fileURL = documentsURL.appendingPathComponent("42535.jpg")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(mjString, to: destination).response { response in
// print(response)
if response.error == nil, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
self.mjImage.image = image
print("imagePath = \(imagePath)")
}
}
file:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg
I want that file to a custom folder, if it is possible. Any help would be appreciated.
The Output what i get is,
file:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg
Append Path Component
just simply change
let fileURL = documentsURL.appendingPathComponent("42535.jpg")
to
let fileURL = documentsURL.appendingPathComponent("/yourFolder/42535.jpg")
EDIT
You can load this image with this function:
func loadImageFromDocumentDirectory(nameOfImage : String, folder: String) -> UIImage {
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("\(folder)/\(nameOfImage)")
if FileManager.default.fileExists(atPath: (imageURL.path)) {
if let image = UIImage(contentsOfFile: imageURL.path) {
return image
}
}
}
//Load default image if img doesnt exist.
return UIImage.init(named: "something.jpg")!
}
Just simply use it like:
imageView.image = loadImageFromDocumentDirectory(nameOfImage : "42535.jpg", folder: "yourFolder")

swift save file after download Alamofire

download and save file
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
// var fileURL = self.createFolder(folderName: downloadFolderName)
var fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = URL(string : currentFile.link )
fileURL = fileURL.appendingPathComponent((fileName?.lastPathComponent)!)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(currentDownloadedFile.link , to: destination).response(completionHandler: { (DefaultDownloadResponse) in
print("res ",DefaultDownloadResponse.destinationURL!);
completion(true)
})
but when i wont to check file in this dirrectory i get nil
let filemanager:FileManager = FileManager()
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let files = filemanager.enumerator(atPath: fileURL.absoluteString) // = nil
while let file = files?.nextObject() {
print(file)
}
if i save local path to file and after reload app wont to share it -> "share" app cant send file (mb cant found it)
can u pls help me. how it works ? why when i print all files he didnt find it? how to save file who after reboot app it will be saved in same link
You are using the wrong API
For file system URLs use always path, absoluteString returns the full string including the scheme (e. g. file:// or http://)
let files = filemanager.enumerator(atPath: fileURL.path)