SWIFT: preventing file backups on iCloud

How to prevent iCloud backup in my application. For this I tried with NSFileManager.   And also 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 this gives me an error: error of an additional argument when called

Now to call the specified function ...

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

+4
source share
3 answers

Swift 1.x. , Swift 2.x, SWIFT . :

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

callsite , :

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

    /// prevent pack up to iCloud for file.By setting this property to true,
     this file will not be backed up to iCloud.
    ///
    /// - Parameter filePath: prevented iCloud backup filePath.
    func preventiCloudBackupForFile(filePath:String) {
        do {
            let url = URL(fileURLWithPath: filePath)
            try FileManager.default.addSkipBackupAttributeToItemAtURL(url: url as NSURL)
        } catch {
            // Handle error here
            print("Error: \(error)")
        }
    }
}

FileManager.

extension FileManager{
    func addSkipBackupAttributeToItemAtURL(url:NSURL) throws {
        try url.setResourceValue(true, forKey: URLResourceKey.isExcludedFromBackupKey)
    }
}

. : test.png

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("test.png").path
DiskHelper().preventiCloudBackupForFile(filePath: filePath)
+1

version of Swift 3

do {
     var resourceValues = URLResourceValues()
      resourceValues.isExcludedFromBackup = true
      try url.setResourceValues(resourceValues)
} catch {
      print(error.localizedDescription)
}
+1
source

Source: https://habr.com/ru/post/1628978/


All Articles