See Image as referenceI am working on a project, in which i need to show a UICollectionview, which includes files from filemanager, in this collectionview i am displaying images as well as folders. And there is also a button which deletes the selected cells.
So how can i delete selected folder/images from document directory?
I am creating folder with this function.
func createDir() {
let manager = FileManager.default
guard let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
print("url path is ==>>",url.path)
let folderName = url.appendingPathComponent(folderNameTextField.text!)
do {
try manager.createDirectory(at: folderName, withIntermediateDirectories: true, attributes: [:])
print("Saved")
listFilesFromDocumentsFolder()
// getAllDirectoriesList()
}
catch {
print(error)
}
}
`And saving images with this function
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
//
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)
}
}
}
I am using this function to delete, it works but abnormally,
for file in folderImageArray {
try! FileManager.default.removeItem(at: file)
}
And
This function making a crash.
for file in folderNameArray {
try! FileManager.default.removeItem(atPath: file)
}
You should not force unwrap try block, Use do try at-least it will give you the reason why it's not working.
Also adding a little delay will work fine
for file in folderImageArray {
do {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
try FileManager.default.removeItem(at: file)
}
} catch {
print("File Deletion Failed: \(error.localizedDescription)")
}
}
Related
I have an issues in changing the file path at every launch of the app.
I have a file("AppConstant.json") in application bundle, and this file I need to copy into application document directory. I am successfully saving "AppConstant.json" file inside the created user folder "MyFolder" on Document directory.
But the problem is when I relaunch the application second time, it's not showing the same path. Also I am using relativepath, but still it not getting.
here is the code
// calling the directory
let stringAppConstant = copyFileFromBundleToDocumentDirectory(resourceFile: "AppConstant", resourceExtension: "json")
// saving or get exit file path
func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) -> String
{
var stringURLPath = "Error_URLPath"
let fileManager = FileManager.default
let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
return stringURLPath
}
if !fileManager.fileExists(atPath: newDestPath.path) {
do {
try fileManager.createDirectory(atPath: newDestPath.path,withIntermediateDirectories: true, attributes: nil)
print("Created folder successfully in :::", newDestPath.path)
} catch {
print("Error in creating folder :::",error.localizedDescription);
}
}
else {
print("Folder is already exist!")
}
if fileManager.fileExists(atPath: fullDestPath.path) {
print("File is exist in ::: \(fullDestPath.path)")
stringURLPath = fullDestPath.path
}
else {
do {
try fileManager.copyItem(atPath: sourcePath, toPath: fullDestPath.path)
print("Saved file successfully in :::", fullDestPath.path)
stringURLPath = fullDestPath.path
} catch {
print("Error in creating file ::: \(error.localizedDescription)")
}
}
return stringURLPath
}
Please help me, where I need to save the path in Sandbox. Is this right way what I implemented.
I am running in device and simulator, both path are different while relaunch
this is the path for first time launch:
/var/mobile/Containers/Data/Application/81B568A7-0932-4C3E-91EB-9DD62416DFE8/Documents/MyFolder/AppConstant.json
relaunch the application I am getting new path:
/var/mobile/Containers/Data/Application/3DAABAC3-0DF5-415B-82A5-72B204311904/Documents/MyFolder/AppConstant.json
NOTE: I create a sample project and I use this same code and it's working. But in existing project it's not working. I am using the same bundle id and profile only for both sample and project. Checked the file added reference, settings, version all are same.
Any idea?
The behavior that the container path changes periodically is normal.
These lines
let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
return stringURLPath
}
contain a lot of mistakes
URL(string is the wrong API for file paths, it's URL(fileURLWithPath).
The second parameter of path(forResource:ofType:) must not have a leading dot.
The API absoluteString is wrong as parameter of URL(fileURLWithPath
Not a real mistake but don't use NSURL in Swift.
It's highly recommended to use always the URL related API to concatenate paths and get the documents folder from FileManager. Further it's good practice to make the method throw the real error rather than returning a meaningless literal string. And NSSearchPathForDirectoriesInDomains is outdated and should not be used in Swift.
func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) throws -> URL
{
let sourceURL = Bundle.main.url(forResource: resourceFile, withExtension: resourceExtension)!
let fileManager = FileManager.default
let destFolderURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("MyFolder")
let fullDestURL = destFolderURL.appendingPathComponent(resourceFile).appendingPathExtension(resourceExtension)
if !fileManager.fileExists(atPath: destFolderURL.path) {
try fileManager.createDirectory(at: destFolderURL, withIntermediateDirectories: true, attributes: nil)
print("Created folder successfully in :::", destFolderURL.path)
try fileManager.copyItem(at: sourceURL, to: fullDestURL)
print("Saved file successfully in :::", fullDestURL.path)
} else {
print("Folder already exists!")
if fileManager.fileExists(atPath: fullDestURL.path) {
print("File exists in ::: \(fullDestURL.path)")
} else {
try fileManager.copyItem(at: sourceURL, to: fullDestURL)
print("Saved file successfully in :::", fullDestURL.path)
}
}
return fullDestURL
}
Edit 1:
Hi I created the new project and use the same code I posted in main, and it's working. But in the real project it not working.
Not sure what exactly going on in your project, try to debug it. It's part of development as well. :)
If you are in hurry to fix this issue in this weekend try to use the following code snippet.
// collect data from bundle
let constFileURL = Bundle.main.url(forResource: "AppConst", withExtension: "json")!
let data = try! Data(contentsOf: constFileURL)
// try to write data in document directory
do {
let constFileURL = try saveFileInDocumentDirectory(filePath: "MyFolder/AppConst.json", data: data)
// use your `constFileURL`
} catch (let error as FileOperationError) {
switch error {
case .fileAlreadyExists(let url):
let data = try! Data(contentsOf: url)
print(String(data: data, encoding: .utf8))
case .IOError(let error):
print("IO Error \(error)")
}
} catch {
print("Unknown Error \(error)")
}
// Helpers
enum FileOperationError: Error {
case fileAlreadyExists(url: URL)
case IOError(Error)
}
func saveFileInDocumentDirectory(filePath: String, data: Data) throws -> URL {
// final destination path
let destURLPath = fullURLPathOf(filePath, relativeTo: .documentDirectory)
// check for file's existance and throw error if found
guard FileManager.default.fileExists(atPath: destURLPath.path) == false else {
throw FileOperationError.fileAlreadyExists(url: destURLPath)
}
// Create Intermidiate Folders
let intermidiateDicPath = destURLPath.deletingLastPathComponent()
if FileManager.default.fileExists(atPath: intermidiateDicPath.path) == false {
do {
try FileManager.default.createDirectory(at: intermidiateDicPath, withIntermediateDirectories: true, attributes: nil)
} catch {
throw FileOperationError.IOError(error)
}
}
// File Writing
do {
try data.write(to: destURLPath, options: .atomic)
} catch {
throw FileOperationError.IOError(error)
}
return destURLPath
}
func fullURLPathOf(_ relativePath: String, relativeTo dic:FileManager.SearchPathDirectory ) -> URL {
return FileManager.default.urls(for: dic, in: .userDomainMask).first!.appendingPathComponent(relativePath)
}
Original Answer
Why don't you just return "MyFolder/\(fileName)" on successful file operation? If you need to access the path later you can always do that using FileManager APIs.
let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let constFilePath = docDir.appendingPathComponent("MyFolder/\(fileName)")
// Access const file data
do {
let fileData = try Data(contentsOf: constFilePath)
// Use you data for any further checking
} catch {
// Error in reading file data
print("Error in file data access : \(error)")
}
I want to upload an image to iCloud drive from my ios app. Upto now I have upload the images by saving them locally in iCloud drive in the device and syncing it to the iCloud. here is the code i have tried.
if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: nil)) {
do{
try FileManager.default.createDirectory(at: iCloudDocumentsURL, withIntermediateDirectories: true, attributes: nil)
}catch let error {
print(error.localizedDescription)
}
}
}
let localDocumentsURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: .userDomainMask).last! as NSURL
let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("MyArtworks")
let image = UIImage(named: "testpoto2") as UIImage?
// get the documents directory url
// choose a name for your image
let fileName = "image6.png"
// create the destination file url to save your image
let fileURL = localDocumentsURL.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
if !FileManager.default.fileExists(atPath: fileURL!.path) {
do {
try UIImagePNGRepresentation(image!)!.write(to: fileURL!)
print("Image Added Successfully")
} catch {
print(error)
}
} else {
print("Image Not Added")
}
if let iCloudDocumentsURL = iCloudDocumentsURL {
var isDir:ObjCBool = false
if (FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: &isDir)) {
do{
try FileManager.default.removeItem(at: iCloudDocumentsURL)
}catch let error {
print(error.localizedDescription)
}
}
do{
try FileManager.default.copyItem(at: localDocumentsURL as URL , to: iCloudDocumentsURL)
}catch let error {
print(error.localizedDescription)
}
}
But I need to save the images directly to the iCloud. Any suggestions are appreciated.
I am trying to download an audio file from the internet and save it onto the phone. This is the download function:
func download() {
if let audioUrl = downloadUrl {
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
print(destinationUrl)
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("The file already exists at path")
// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: location, to: destinationUrl)
print("File moved to documents folder")
} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
}
}
Then, after I close and open the app, I use the following function to retrieve the url and play it using an AVPlayer:
func getUrl2() {
if let audioUrl = downloadUrl {
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
if let u = self.destinationUrl {
let player = AVPlayer(url: u)
print(u)
print("Bouta play")
print(CMTimeGetSeconds(player.currentItem!.duration))
player.play()
}
}
}
The duration that keeps getting printed out is "nan". Is there a way to check if the audio file is actually downloading? Or could it be a problem with retrieving the file after the download? Thanks in advance.
First of all you have to check for the URL is not empty with the below logic:
if !link.isEmpty{
checkBookFileExists(withLink: link){ [weak self] downloadedURL in
guard let self = self else{
return
}
play(url: downloadedURL)
}
}
Then checkBookFileExists function will check if the file already saved or not before download it again:
func checkBookFileExists(withLink link: String, completion: #escaping ((_ filePath: URL)->Void)){
let urlString = link.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
if let url = URL.init(string: urlString ?? ""){
let fileManager = FileManager.default
if let documentDirectory = try? fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create: false){
let filePath = documentDirectory.appendingPathComponent(url.lastPathComponent, isDirectory: false)
do {
if try filePath.checkResourceIsReachable() {
print("file exist")
completion(filePath)
} else {
print("file doesnt exist")
downloadFile(withUrl: url, andFilePath: filePath, completion: completion)
}
} catch {
print("file doesnt exist")
downloadFile(withUrl: url, andFilePath: filePath, completion: completion)
}
}else{
print("file doesnt exist")
}
}else{
print("file doesnt exist")
}
}
Then if the file doesn't exists you will download it with the below function:
func downloadFile(withUrl url: URL, andFilePath filePath: URL, completion: #escaping ((_ filePath: URL)->Void)){
DispatchQueue.global(qos: .background).async {
do {
let data = try Data.init(contentsOf: url)
try data.write(to: filePath, options: .atomic)
print("saved at \(filePath.absoluteString)")
DispatchQueue.main.async {
completion(filePath)
}
} catch {
print("an error happened while downloading or saving the file")
}
}
}
That function will save it and you can play it with:
func play(url: URL) {
print("playing \(url)")
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.prepareToPlay()
audioPlayer?.delegate = self
audioPlayer?.play()
let percentage = (audioPlayer?.currentTime ?? 0)/(audioPlayer?.duration ?? 0)
DispatchQueue.main.async {
// do what ever you want with that "percentage"
}
} catch let error {
audioPlayer = nil
}
}
I am making an audio app, and the user can download files locally stored to the documentDirectory using FileManager.
Next, I'd like to allow the user to delete all files using a button. In the documentation, there is a method to remove items.
Here's my code:
#IBAction func deleteDirectoryButton(_ sender: Any) {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
try FileManager.default.removeItem(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
} catch let error {
print(error)
}
}
Unfortunately, this won't build with an error Ambiguous reference to member 'removeItem(atPath:)'.
Is there a better approach to access the documentDirectory and remove all files from the directory in one swoop?
First of all the error occurs because the signature of the API is wrong. It's just removeItem(at:) without the other parameters.
A second issue is that you are going to delete the Documents directory itself rather than the files in the directory which you are discouraged from doing that.
You have to get the contents of the directory and add a check for example to delete only MP3 files. A better solution would be to use a subfolder.
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsUrl,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
for fileURL in fileURLs where fileURL.pathExtension == "mp3" {
try FileManager.default.removeItem(at: fileURL)
}
} catch { print(error) }
Side note: It is highly recommended to use always the URL related API of FileManager.
Try this
func clearAllFiles() {
let fileManager = FileManager.default
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
print("Directory: \(paths)")
do {
let fileName = try fileManager.contentsOfDirectory(atPath: paths)
for file in fileName {
// For each file in the directory, create full path and delete the file
let filePath = URL(fileURLWithPath: paths).appendingPathComponent(file).absoluteURL
try fileManager.removeItem(at: filePath)
}
} catch let error {
print(error)
}
}
Just use code as Follow
to save AudioFile in Document Directory as
func getDocumentsDirectory() -> URL
{
//Get Basic URL
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
/// Enter a Directory Name in which files will be saved
let dataPath1 = documentsDirectory.appendingPathComponent("folder_name_enter")
let dataPath = dataPath1.appendingPathComponent("folder inside directory if required (name)")
//Handler
do
{
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
print("Error creating directory: \(error.localizedDescription)")
}
return dataPath
}
Delete
func clearAllFilesFromTempDirectory()
{
let fileManager = FileManager.default
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let tempDirPath = dirPath.appending("/folder_name/\(inside_directoryName)")
do {
let folderPath = tempDirPath
let paths = try fileManager.contentsOfDirectory(atPath: tempDirPath)
for path in paths
{
try fileManager.removeItem(atPath: "\(folderPath)/\(path)")
}
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
Saving Method
getDocumentsDirectory().appendingPathComponent("\(audioName).wav")
Deletion Method
/// Just call
clearAllFilesFromTempDirectory
This my extension for remove all files and caches from directory.
// MARK: - FileManager extensions
extension FileManager {
/// Remove all files and caches from directory.
public static func removeAllFilesDirectory() {
let fileManager = FileManager()
let mainPaths = [
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).map(\.path)[0],
FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).map(\.path)[0]
]
mainPaths.forEach { mainPath in
do {
let content = try fileManager.contentsOfDirectory(atPath: mainPath)
content.forEach { file in
do {
try fileManager.removeItem(atPath: URL(fileURLWithPath: mainPath).appendingPathComponent(file).path)
} catch {
// Crashlytics.crashlytics().record(error: error)
}
}
} catch {
// Crashlytics.crashlytics().record(error: error)
}
}
}
}
Swift 5
Delete the whole folder:
If you'd like to delete a whole folder you can simply do this:
func deleteFolder(_ folderName: String, completion: () -> Void) {
let fileManager = FileManager.default
let directory = fileManager.cachesDirectory().appendingPathComponent(folderName)
_ = try? fileManager.removeItem(at: directory)
completion()
}
Delete certain files based on their name:
This will loop through all the files and remove all that contain the
func removeFiles(containing: String, completion: () -> Void) {
let fileManager = FileManager.default
let directory = fileManager.cachesDirectory()
if let fileNames = try? fileManager.contentsOfDirectory(atPath: directory.path) {
for file in fileNames {
if file.contains(containing) {
let filePath = URL(fileURLWithPath: directory.path).appendingPathComponent(file).absoluteURL
_ = try? fileManager.removeItem(at: filePath)
}
}
}
completion()
}
I'm trying to retrieve images from the documents directory in order to populate a collection view but my try block returns an error but I don't know what the error is or why it is occurring.
func refreshCollectionView() {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.appendingPathComponent(imagesDirectoryPath)?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath!) {
print("FILE AVAILABLE")
do {
titles = try FileManager.default.contentsOfDirectory(atPath: imagesDirectoryPath)
print(titles.count)
for image in titles {
let data = FileManager.default.contents(atPath: imagesDirectoryPath + "/\(image)")
let image = UIImage(data: data!)
myImages.append(image!)
}
self.collectionView?.reloadData()
}
catch {
print("Error")
}
}
else {
print("FILE NOT AVAILABLE")
}
}
The line print(titles.count) is never executed and the error is caught but what is the error?
if fileManager.fileExists(atPath: filePath!) {
print("FILE AVAILABLE")
do {
// ...
} catch {
print("Error:", error)
}
}
This will show you actual error