How to Read File Data Applications Document Directory in Swift

How to read file data Applications document directory in swift?

For Swift 2 you have to change something. Note: stringByAppendingPathComponent is not more available on String (only NSString):

var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var getImagePath = paths.stringByAppendingPathComponent("filename")
myImageView.image = UIImage(contentsOfFile: getImagePath)

How can I display my App documents in the Files app for iPhone

If you would like to expose your App document files inside Apple's Files App you need to include the "Supports Document Browser" key in your info plist file and set it to YES:

Sample Image

Getting list of files in documents folder

This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}

Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:

import Foundation

extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}

// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")

How to get all the files from Applications document directory in swift?

do{
let files = try FileManager.default.contentsOfDirectory(atPath: documentsDirectory)
for filename in files {
print(filename)
}
}
catch {
print(error.localizedDescription)
}

iOS - Can't Read File Located In Documents Directory

You have a permissions error. You don't have the right permissions to open the file. Wherever you got it from, you're locked out. You might try to download it in the simulator, and check it through Apple's file system to see what permissions it actually downloaded with. The path is:

~/Library/Developer/CoreSimulator/Devices//data/Containers/Data/Application//Documents.

Replace the two big random strings with the directories that show a mod date of today, or NSLog the real path from your iOS app.

Get File List from sub folder of Documents Directory swift ios

This is the working code..

func listFilesFromDocumentsFolder() -> [String]
{
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

if dirs != nil {
let dir = dirs![0]//this path upto document directory

//this will give you the path to MyFiles
let MyFilesPath = dir.stringByAppendingPathComponent("/BioData")
if !NSFileManager.defaultManager().fileExistsAtPath(MyFilesPath) {
NSFileManager.defaultManager().createDirectoryAtPath(MyFilesPath, withIntermediateDirectories: false, attributes: nil, error: theError)
} else {
println("not creted or exist")
}

let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(MyFilesPath, error: theError) as! [String]

var count = fileList.count
for var i = 0; i < count; i++
{
var filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
filePath = filePath.stringByAppendingPathComponent(fileList[i])
let properties = [NSURLLocalizedNameKey, NSURLCreationDateKey, NSURLContentModificationDateKey, NSURLLocalizedTypeDescriptionKey]
var attr = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: NSErrorPointer())
}
println("fileList: \(fileList)")
return fileList.filter{ $0.pathExtension == "pdf" }.map{ $0.lastPathComponent } as [String]
}else{
let fileList = [""]
return fileList
}
}

How to use folders in swift not visible to users?

Well the most popular option to save a file in iOS is saving in document directory of the application.

A document directory is a directory where you can save all possible files and folders what you want, and the files are completely safe from other applications, meaning, iOS doesn't permit any application to write in other's document directory. Moreover, users won't find the directory as like android.

To save a file in the document directory, for example an image file

let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = documentDirectory.appendingPathComponent(name)
let image = #imageLiteral(resourceName: "Notifications")
if let imageData = image.jpegData(compressionQuality: 0.5) {
try imageData.write(to: fileURL)
return true
}
} catch {
print(error)
}

to remove the file from document directory

let fileManager = FileManager.default
do {
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for url in fileURLs {
try fileManager.removeItem(at: url)
}
} catch {
print(error)
}

How to get NSURL on specific file from document directory in swift

I found a solution for my question

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var playerVC = (segue.destinationViewController as! UINavigationController).topViewController as! PlayMusicViewController
var indexPath = tableView.indexPathForSelectedRow()
var objectForPass = listOfMP3Files![indexPath!.row] // default
//

/* var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as? String
var getImage = path?.stringByAppendingPathComponent(objectForPass)
var image = UIImage(contentsOfFile: getImage!) */
//
var fileM = NSFileManager.defaultManager()

var wayToFile = fileM.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var passMusicFileURL: NSURL?

if let documentPath: NSURL = wayToFile.first as? NSURL {
let musicFile = documentPath.URLByAppendingPathComponent(objectForPass)
println(musicFile)
passMusicFileURL = musicFile
}
if segue.identifier == "listenMusic" {
// playerVC.musicFile = objectForPass
playerVC.end = passMusicFileURL
}
}


Related Topics



Leave a reply



Submit