iOS Securing Data in iTunes Backups


Example

If we want our app data to be protected against iTunes backups, we have to skip our app data from being backed up in iTunes.
Whenever iOS device backed up using iTunes on macOS, all the data stored by all the apps is copied in that backup and stored on backing computer.

But we can exclude our app data from this backup using URLResourceKey.isExcludedFromBackupKey key.
Here is the directory structure of our app: enter image description here
Note: Generally sensitive data is stored in 'Application Support' directory.

e.g. If we want to exclude all our data stored in Application Support directory then we can use above mentioned key as follow:

    let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
    let baseURL = urls[urls.count-1];
    
    let bundleIdentifier = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as! String
    let pathURL = baseURL.appendingPathComponent(bundleIdentifier)
    let persistentStoreDirectoryPath = pathURL.path
    if !FileManager.default.fileExists(atPath: persistentStoreDirectoryPath) {
        do {
            try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)  
        }catch {
            //handle error
        }
    }
    let dirURL = URL.init(fileURLWithPath: persistentStoreDirectoryPath, isDirectory: true)
    do {
        try (dirURL as NSURL).setResourceValue((true), forKey: .isExcludedFromBackupKey)
    } catch {
        //handle error
    }

There are lots of tools available to see iTunes backups for all the backed up data to confirm whether above approach works or not.
iExplorer is good one to explore iTunes backups.