Search code examples
iosswifticloudnsurl

SWIFT : Prevent backup files on iCloud


How do I prevent iCloud backup in my app. For that I tried with NSFileManager. And How to implement addSkipBackupAttributeToItemAtURL in Swift?

I tried with this stuff

extension NSFileManager{
    func addSkipBackupAttributeToItemAtURL(url:NSURL)->Bool{
        var error:NSError?
        let success:Bool = url.setResourceValue(NSNumber.numberWithBool(true), forKey: NSURLIsExcludedFromBackupKey, error: &error);
        return success;
    }
}

But it gives me error : Extra argument error in call

Now for calling the above function...

NSFileManager.defaultManager().addSkipBackupAttributeToItemAtURL(NSURL.fileURLWithPath());


Solution

  • Your code looks like Swift 1.x syntax. Assuming you're using Swift 2.x, you need to use the native Swift error-handling syntax. Like this:

    extension NSFileManager{
        func addSkipBackupAttributeToItemAtURL(url:NSURL) throws {
            try url.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey)
        }
    }
    

    At the callsite, you need to handle the error like this:

    do {
        let url = ... // the URL of the file
        try NSFileManager.defaultManager().addSkipBackupAttributeToItemAtURL(url)
    } catch {
        // Handle error here
        print("Error: \(error)")
    }