iOS file path is changing at every launch/rerun the application - ios

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

Related

SwiftUI | File found on simulator but not on iOS device

I'm trying to create a connection between my program and a database located in /Documents of the app. When the code is built using on the simulator, it successfully opens the database; however, when I run the code on an iOS device, it can't find the file.
This is the code that I use:
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
let db = try! Connection("\(path)/Database.db")
These are the contents of the variable path when I run the code on the simulator:
/Users/xxxx/Library/Developer/CoreSimulator/Devices/EFD14A1B-7207-4840-9ACE-8E44A269CC70/data/Containers/Data/Application/58D150B9-E242-4857-B06C-DA28C88A26D0/Documents
And these are the contents of the variable path when I run the code on an iOS device:
/var/mobile/Containers/Data/Application/4EC93D76-4E99-4552-855A-48C1D9346449/Documents
Xcode version: 12.0
iOS device: iPhone X
iOS version: 14.1
Edit
I tried to use this code to copy the database from the app bundle to the document directory, but it gives the error Unable to copy file:
copyFileToDocumentsFolder(nameForFile: "Database", extForFile: "db")
func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destURL = documentsURL.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
else {
print("Source File not found.")
return
}
let fileManager = FileManager.default
do {
try fileManager.copyItem(at: sourceURL, to: destURL)
} catch {
print("Unable to copy file")
}
}
You can use url or path: with this codes you get the address of your data base, but you have to have your database file already there when your app use this address to find your databace! if you use this address, without having real file there, your app will crash. So if you have problem about copying your databace file let me know!
Version: 1.0.0
let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let databaseURL = appBaseURL.appendingPathComponent("Database").appendingPathExtension("db").standardizedFileURL
let databasePath = databaseURL.path
Update Version: 2.0.0
This codes down are the most simplest and cleanest code about copy and paste on planet Earth for Swift and SwiftUI! You can not find better than this:
// If you want see your file in device or give user access to the file do this 2 steps:
// 1 - add this one ("Application supports iTunes file sharing" -> Yes) from (info.plist)
// 2 -add this one ("Supports opening documents in place" -> Yes) from (info.plist)
let fileName = "omid"
let fileExtension = "jpeg"
let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let pasteFileURL = appBaseURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
let copyFileURL = Bundle.main.bundleURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
if FileManager.default.fileExists(atPath: appBaseURL.path)
{
print("appBaseFolder already exists!")
}
else
{
do{ try FileManager.default.createDirectory(at: appBaseURL, withIntermediateDirectories: true, attributes: nil); print("appBaseFolder successfully created!") }
catch{ print("Error in creating appBaseFolder!") }
}
if FileManager.default.fileExists(atPath: pasteFileURL.path)
{
print("The selected file already exists!")
}
else
{
do{ try FileManager.default.copyItem(at: copyFileURL, to: pasteFileURL); print("The selected file successfully copied!") }
catch { print("Error with copying selected file!") }
}
Version: 3.0.0 (The GM Version)
//▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// If you want see your file in device or give user access to the file do this 2 steps:
// 1 - add this one ("Application supports iTunes file sharing" -> Yes) from (info.plist)
// 2 - add this one ("Supports opening documents in place" -> Yes) from (info.plist)
//...........................................................
let fileName = "omid"
let fileExtension = "jpeg"
//...........................................................
let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let pasteFileURL = appBaseURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
let copyFileURL = Bundle.main.bundleURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
//▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//...........................................................
if FileManager.default.fileExists(atPath: appBaseURL.path)
{
print("appBaseFolder already exists!")
}
else
{
do{ try FileManager.default.createDirectory(at: appBaseURL, withIntermediateDirectories: true, attributes: nil); print("appBaseFolder successfully created!") }
catch{ print("Error in creating appBaseFolder!") }
}
//...........................................................
//...........................................................
if FileManager.default.fileExists(atPath: copyFileURL.path)
{
//...........................................................
if FileManager.default.fileExists(atPath: pasteFileURL.path)
{
print("The selected file already exists!")
}
else
{
do{ try FileManager.default.copyItem(at: copyFileURL, to: pasteFileURL); print("The selected file successfully copied!") }
catch { print("Error with copying selected file!") }
}
//...........................................................
}
else
{
print("The selected file not exists for copy Action!")
}
//...........................................................
As I already mentioned in your last question the Bundle is read-only. you need to move/copy your database to another directory that you can read/write to it. If you don't want the user to have access to the file you should copy it to that application support directory:
extension URL {
static let database: URL = {
let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let bundleID = Bundle.main.bundleIdentifier ?? "company name"
let subDirectory = applicationSupport.appendingPathComponent(bundleID, isDirectory: true)
let destination = subDirectory.appendingPathComponent("Database.db")
if !FileManager.default.fileExists(atPath: destination.path) {
let source = Bundle.main.url(forResource: "Database", withExtension: "db")!
do {
try FileManager.default.createDirectory(at: subDirectory, withIntermediateDirectories: true, attributes: nil)
print("directory created")
try FileManager.default.copyItem(at: source, to: destination)
print("file copied successfully")
} catch {
print("Unable to copy file. return the bundle read-only version")
return source
}
}
print("database found return app suport database read-write url")
return destination
}()
}
let dbURL = URL.database
The Mac (and by extension the Simulator) has a case-insensitive file system. iOS has a case-sensitive file system. If it's working on the simulator, but not the device, I expect the capitalization of your database filename is incorrect. The most likely mistake would be that it's database.db rather than Database.db.

Where is the file saved with the path .documentDirectory

As the titel rleaves. I'm facing the issue, that I have no clue how to save the csv file to the document of the devices so I can get accesse outside my app. Can any body help?
So far I tried this code.
func creatCSV() -> Void {
let fileName = "Tasks.csv"
do {
guard let path = try? FileManager.default.url(
for: .documentDirectory,
in: .allDomainsMask,
appropriateFor: nil,
create: false
).appendingPathComponent(fileName) as NSURL else {
return
}
var csvText = "Date,Task Name,Time Started,Time Ended\n"
for task in taskArr {
let newLine = "\(task.date),\(task.name),\(task.startTime),\(task.endTime)\n"
csvText.append(newLine)
}
try csvText.write(to: path as URL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
print("not found")
}
But I have no clue where I finde the file after I called the funtion.
Long story short: You have to set in "info.plist" "Application supports iTunes file sharing" to "YES"

Swift delete all files from particular Document Directory Location

My Scenario, I am trying to delete all files from particular document directory by using document folder path. Here, every time I am saving file within my application document directory folder, by using below code I can’t able to delete files
let urlString: String = myurl.absoluteString
print("FILEURL:\(urlString)")
do {
try fm.removeItem(atPath: "\(myurl)")
} catch let error as NSError {
print(error.debugDescription)
}
You are mixing up URL and String path
Either use the String related API
try fm.removeItem(atPath: myurl.path) // NEVER use .absoluteString for a file system path
or use the URL related API (recommended)
try fm.removeItem(at: myurl)
To remove all files get the file URLs in the enclosing directory with contentsOfDirectory(at:includingPropertiesForKeys:options:) and remove one by one
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)
}
For delete specific file or folder using Url
let filePathString = "file:///Users/mac-01/Library/Developer/CoreSimulator/Devices/092D2386-5B43-4D98-8DCF-F21E08CCD400/data/Containers/Data/Application/C6D910A2-67D9-48A4-8221-5C81C722D508/Documents/Products"
guard let fileUrl = URL(string: "\(filePathString)") else { return }
do {
try FileManager.default.removeItem(at: fileUrl)
print("Remove successfully")
}
catch let error as NSError {
print("An error took place: \(error)")
}
removeItem method is accept url of document directory file or folder.Please try with it.
For Delete Document directory folder use
let fileManager = FileManager.default
let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
try fileManager.removeItem(at: myDocuments)
} catch {
return
}

Sharing data between a WatchKit App and the containing iOS App is not working

I'm trying to share file originally generated in watch App Extension but it's not working. I am using iOS 11.3 and Watch 4.3. I am also using Simulator.
I have done like this
Enable App domain in Main app and Watch App Extension.
App domain in selected in both with identifier.
REF : https://www.techotopia.com/index.php/Sharing_Data_Between_a_WatchKit_App_and_the_Containing_iOS_App
Code added:
In Watch App Extension:
do {
let fileManager = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppDomain)
guard let url = fileManager?.appendingPathComponent("TabCareLogs.txt") else { return }
try SOME_STRING.appendLineToURL(fileURL: url)
print("WatchKit: FILE PATH \(url.path)")
let result = try String(contentsOf: url, encoding: .utf8)
debugPrint("############# FILE: \(result) #############")
} catch let error {
print("Could not write to file : \(error.localizedDescription)")
}
extension String {
func appendLineToURL(fileURL: URL) throws {
try (self + "\n").appendToURL(fileURL: fileURL)
}
func appendToURL(fileURL: URL) throws {
let data = self.data(using: .utf8)!
try data.append(fileURL: fileURL)
}
}
extension Data {
func append(fileURL: URL) throws {
if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
}
else {
try write(to: fileURL, options: .atomic)
}
}
}
WatchKit: FILE PATH
/Users/abhishek/Library/Developer/CoreSimulator/Devices/D515C513-3975-4C8F-B07D-6A0CCCD1A8EC/data/Containers/Shared/AppGroup/90DC2A1A-61D6-440B-A499-9EA608CE0C2E/TabCareLogs.txt
I'm getting file as well as its content.
In Main App:
let fileManager = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppDomain)
guard let url = fileManager?.appendingPathComponent("TabCareLogs.txt") else { return nil }
print("FILE PATH \(url.path)")
print("FILE PATH ABSOLUTE \(url.absoluteString)")
let exists = FileManager.default.fileExists(atPath: url.path)
print("FILE EXIST : \(exists)")
FILE PATH
/Users/abhishek/Library/Developer/CoreSimulator/Devices/D5CED7C4-B674-4BF7-A72C-C063F733F4E7/data/Containers/Shared/AppGroup/77C1EAC2-2A86-4763-973F-33929C909619/TabCareLogs.txt
FILE PATH ABSOLUTE
file:///Users/abhishek/Library/Developer/CoreSimulator/Devices/D5CED7C4-B674-4BF7-A72C-C063F733F4E7/data/Containers/Shared/AppGroup/77C1EAC2-2A86-4763-973F-33929C909619/TabCareLogs.txt
FILE EXIST : false
I have tried to print the path I'm getting path bit if I'm checking file exist then its is showing false.
Same issue : NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
Also the paths are different I don't know why it is going to different path after using shared container?

Remove all files from within documentDirectory in Swift

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

Resources