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)
Related
I know there are a few questions pertaining to this, but they're in Objective-C.
How can I access a .txt file included in my app using Swift on an actual iPhone? I want to be able to read and write from it. Here are my project files if you want to take a look. I'm happy to add details if necessary.
Simply by searching in the app bundle for the resource
var filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")
However you can't write to it because it is in the app resources directory and you have to create it in the document directory to write to it
var documentsDirectory: NSURL?
var fileURL: NSURL?
documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last!
fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")
if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
print("file exist")
}else{
print("file doesnt exist")
NSData().writeToURL(fileURL!,atomically:true)
}
now you can access it from fileURL
EDIT - 28 August 2018
This is how to do it in Swift 4.2
var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")
To create it in the document directory
if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let fileURL = documentsDirectory.appendingPathComponent("file.txt")
do {
if try fileURL.checkResourceIsReachable() {
print("file exist")
} else {
print("file doesnt exist")
do {
try Data().write(to: fileURL)
} catch {
print("an error happened while creating the file")
}
}
} catch {
print("an error happened while checking for the file")
}
}
Swift 3, based on Karim’s answer.
Reading
You can read files included in an app’s bundle through the bundle’s resource:
let fileURL = Bundle.main.url(forResource:"filename", withExtension: "txt")
Writing
However, you can’t write there. You will need to create a copy, preferably in the Documents directory:
func makeWritableCopy(named destFileName: String, ofResourceFile originalFileName: String) throws -> URL {
// Get Documents directory in app bundle
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
fatalError("No document directory found in application bundle.")
}
// Get URL for dest file (in Documents directory)
let writableFileURL = documentsDirectory.appendingPathComponent(destFileName)
// If dest file doesn’t exist yet
if (try? writableFileURL.checkResourceIsReachable()) == nil {
// Get original (unwritable) file’s URL
guard let originalFileURL = Bundle.main.url(forResource: originalFileName, withExtension: nil) else {
fatalError("Cannot find original file “\(originalFileName)” in application bundle’s resources.")
}
// Get original file’s contents
let originalContents = try Data(contentsOf: originalFileURL)
// Write original file’s contents to dest file
try originalContents.write(to: writableFileURL, options: .atomic)
print("Made a writable copy of file “\(originalFileName)” in “\(documentsDirectory)\\\(destFileName)”.")
} else { // Dest file already exists
// Print dest file contents
let contents = try String(contentsOf: writableFileURL, encoding: String.Encoding.utf8)
print("File “\(destFileName)” already exists in “\(documentsDirectory)”.\nContents:\n\(contents)")
}
// Return dest file URL
return writableFileURL
}
Example usage:
let stuffFileURL = try makeWritableCopy(named: "Stuff.txt", ofResourceFile: "Stuff.txt")
try "New contents".write(to: stuffFileURL, atomically: true, encoding: String.Encoding.utf8)
Just a quick update for using this code with Swift 4:
Bundle.main.url(forResource:"YourFile", withExtension: "FileExtension")
And the following has been updated to account for writing the file out:
var myData: Data!
func checkFile() {
if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let fileURL = documentsDirectory.appendingPathComponent("YourFile.extension")
do {
let fileExists = try fileURL.checkResourceIsReachable()
if fileExists {
print("File exists")
} else {
print("File does not exist, create it")
writeFile(fileURL: fileURL)
}
} catch {
print(error.localizedDescription)
}
}
}
func writeFile(fileURL: URL) {
do {
try myData.write(to: fileURL)
} catch {
print(error.localizedDescription)
}
}
This particular example is not the most flexible, but with a little bit of work you can easily pass in your own file names, extensions and data values.
🎁 Property Wrapper - Fetch and convert to correct data type
This simple wrapper helps you to load any file from any bundle in a cleanest way:
#propertyWrapper struct BundleFile<DataType> {
let name: String
let type: String
let fileManager: FileManager = .default
let bundle: Bundle = .main
let decoder: (Data) -> DataType
var wrappedValue: DataType {
guard let path = bundle.path(forResource: name, ofType: type) else { fatalError("Resource not found: \(name).\(type)") }
guard let data = fileManager.contents(atPath: path) else { fatalError("Can not load file at: \(path)") }
return decoder(data)
}
}
Usage:
#BundleFile(name: "avatar", type: "jpg", decoder: { UIImage(data: $0)! } )
var avatar: UIImage
You can define any decoder to match your needs
Get File From Bundle in Swift 5.1
//For Video File
let stringPath = Bundle.main.path(forResource: "(Your video file name)", ofType: "mov")
let urlVideo = Bundle.main.url(forResource: "Your video file name", withExtension: "mov")
Bundles are read only. You can use NSBundle.mainBundle().pathForResource to access the file as read-only, but for read-write access you need to copy your document to Documents folder or tmp folder.
Bundles can be written. You can use Bundle.main.path to overwrite file by adding it into Copy Bundles Resource.
I have to use a file from another bundle. So, following code worked for me. Needful when you work with a frameworks.
let bundle = Bundle(for: ViewController.self)
let fileName = bundle.path(forResource: "fileName", ofType: "json")
I want to save a MIDI-file to a certain folder. But unfortunately just get an "Untitled" txt file.
I found this code which I tried:
let savePanel = NSSavePanel()
let bundleFile = Bundle.main.url(forResource: "Melody", withExtension: "mid")!
// this is a preferred method to get the desktop URL
savePanel.directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
savePanel.message = "My custom message."
savePanel.nameFieldStringValue = "MyFile"
savePanel.showsHiddenFiles = false
savePanel.showsTagField = false
savePanel.canCreateDirectories = true
savePanel.allowsOtherFileTypes = false
savePanel.isExtensionHidden = false
if let url = savePanel.url, savePanel.runModal() == NSApplication.ModalResponse.OK {
print("Now copying", bundleFile.path, "to", url.path)
// Do the actual copy:
do {
try FileManager().copyItem(at: bundleFile, to: url)
} catch {
print(error.localizedDescription)
} else {
print("canceled")
}
What can I improve to copy the MIDI-File from the Application Bundle to the e.g. Desktop??
Thanks!
Looking over some old code I wrote to copy a file from the app bundle to a location on someone's Mac, I had to append the name of the file as an additional path component to the destination URL to get the file to copy properly. Using your code example, the code would look similar to the following:
let name = "Melody.mid"
// url is the URL the user chose from the Save panel.
destinationURL = url.appendingPathComponent(name)
// Use destinationURL instead of url as the to: argument in FileManager.copyItem.
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")
}
}
I am making a func that edits a text file in the Users/johnDoe Dir.
let filename = "random.txt"
let filePath = "/Users/johnDoe"
let replacementText = "random bits of text"
do {
try replacementText.write(toFile: filePath, atomically: true, encoding: .utf8)
}catch let error as NSError {
print(error: + error.localizedDescription)
}
But I want to be able to have the path universal. Something like
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
but for the JohnDoe folder. I haven't been able to find any documentation on how to do this. The closest thing I could find mentioned using NSHomeDirectory(). And I am not sure how to use it in this context.
when I try adding it like...
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: NSHomeDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
I get an error:
"Cannot Convert value of type 'String' to expected argument type 'FileManager.SearchPathDirectory'"
I've tried it .NSHomeDirectory, .NSHomeDirectory(), NShomeDirectory, NShomeDirectory()
You can use FileManager property homeDirectoryForCurrentUser
let homeDirURL = FileManager.default.homeDirectoryForCurrentUser
If you need it to work with earlier OS versions than 10.12 you can use
let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())
print(homeDirURL.path)
There should be an easier way but -- at worst -- this should work:
let filePath = NSString(string: "~").expandingTildeInPath
Swift 5 (and maybe lower)
let directoryString: String = NSHomeDirectory()
let directoryURL: URL = FileManager.default.homeDirectoryForCurrentUser
Maybe
FileManager.homeDirectoryForCurrentUser: URL
It's listed as "beta" for 10.12, though.
Ok so this one has had me scratching my head for a while.
I have a png file that I write out to disk. I get the data by:
let data = UIImagePNGRepresentation(scaledImage!)
let filename = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png")
I do a try catch and everything seems to work. The resulting filename is:
file:///var/mobile/Containers/Data/Application/C6B796E8-2DB6-45A4-9B18-EF808B8CA3CA/Documents/580420d51800cd826a7e217c.png
The problem comes when I try to load that image back from the disk.
When I get a list of all files in the documents directory I get:
[file:///private/var/mobile/Containers/Data/Application/C6B796E8-2DB6-45A4-9B18-EF808B8CA3CA/Documents/580420d51800cd826a7e217c.png]
The only difference I can see is the 'private' part of the filepath. When I try to check to see if the file exists using the filepath I get back from appending the filename (the one without the private part) I get false.
What am I missing?
Swift 3/4 code
Let us assume the method getDocumentsDirectory() is defined as follows
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
In order to save the image
let data = UIImagePNGRepresentation(scaledImage!)
let filename = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png")
try? data?.write(to: filename)
And your image is saved in Documents Directory
Now in order to load it back
let imagePath = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: imagePath){
print("Image Present")
//load it in some imageView
}else {
print("No Image")
}