This is how I've managed to delete all old plists except the current one I had. It's in Swift 3:
func removeOldPlistFiles() {
let fileManager = FileManager.default
// get directory with your current plist for comparison later
let directory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let destPath = (dir as NSString).appendingPathComponent("YourCurrentPlistName.plist")
// Get the documents directory url
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get the documents directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
// filter the directory contents and get file names
let plistFiles = directoryContents.filter{ $0.pathExtension == "plist" }
let plistFileNames = plistFiles.map{ $0.deletingPathExtension().lastPathComponent }
for nameFile in plistFileNames {
let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let item = (dir as NSString).appendingPathComponent("\(nameFile).plist")
if item != self.destPath! {
do {
try fileManager.removeItem(atPath: item)
}
catch let error as NSError {
print("FimeManager Remove Item error: \(error.debugDescription)")
}
}
}
} catch let error as NSError {
print("Directory Contents error: \(error.localizedDescription)")
}
}
I suppose the code can be better, even though it's functional. If anyone has any insights, please share.