【问题标题】:SWIFT : Prevent backup files on iCloudSWIFT:防止在 iCloud 上备份文件
【发布时间】:2016-05-27 17:54:33
【问题描述】:

如何在我的应用中阻止 iCloud 备份。为此,我尝试使用 NSFileManager。如何在 Swift 中实现 addSkipBackupAttributeToItemAtURL?

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;
    }
}

但它给了我错误:调用中的额外参数错误

现在调用上面的函数...

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

【问题讨论】:

  • 一看到var error:NSError?,您就可以认为它是 Swift 1 的代码。您现在可能正在使用 Swift 2 附带的 Xcode 7。

标签: ios swift icloud nsurl


【解决方案1】:

Swift 3 版本

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

【讨论】:

  • url 来自哪里?是不是要放到application(_application: UIApplication, didFinishLaunchingWithOptions ...方法中?
【解决方案2】:
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)

【讨论】:

    【解决方案3】:

    您的代码看起来像 Swift 1.x 语法。假设你使用的是 Swift 2.x,你需要使用原生的 Swift error-handling syntax。像这样:

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

    在调用点,您需要像这样处理错误:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 2012-01-23
      相关资源
      最近更新 更多