How to detect change in number of files in Documents iOS

I'm trying to make an observer that will run in the background to detect if the number of files in my iOS app's documents folder changed. I've been doing research but I can't find anything that helps.

Replies

to count the files :


        // 1. Get Full path to documents directory
        let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].path

        // 2. List all contents of directory and return as [String] OR nil if failed: quit
        var list: [String] = []
        do {
            list = try FileManager.default.contentsOfDirectory(atPath:docs)
            print("Number of files", list.count)
        } catch {
            print(error)
            return
        }


Note: as explained in doc for contentsOfDirectory

This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”), or resource forks (files that begin with “._”) but it does return other hidden files (files that begin with a period character). If you need to perform a deep enumeration, use the enumerator(at:includingPropertiesForKeys:options:errorHandler:) method instead.


The order of the files in the returned array is undefined.


So, if you want to detect,; just keep the previous count and compare new count.

But, do you want be notidfied of change ? If so, this should help:

https://stackoverflow.com/questions/24150061/how-to-monitor-a-folder-for-new-files-in-swift