当 ubiquitousItemDownloadingStatusKey 为 'Current' 时,我正在尝试 运行 一个函数

I am trying to run a function when ubiquitousItemDownloadingStatusKey is 'Current'

我正在尝试在我的应用程序的 iCloud 无处不在容器中下载一个目录,我想在它完成下载后调用一个函数。我可以获得这样的状态:

func synciCloud(){
    do { try FileManager.default.startDownloadingUbiquitousItem(at: documentsPath)
        do {
            let status = try documentsPath.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey])
            print(status)
        }
        catch let error { print("Failed to get status: \(error.localizedDescription)") }
    }
    catch let error { print("Failed to download iCloud Documnets Folder: \(error.localizedDescription)") }
}

控制台打印:

URLResourceValues(_values: [__C.NSURLResourceKey(_rawValue: NSURLUbiquitousItemDownloadingStatusKey): NSURLUbiquitousItemDownloadingStatusCurrent], _keys: Set([__C.NSURLResourceKey(_rawValue: NSURLUbiquitousItemDownloadingStatusKey)]))

我困惑的是 NSMetadata 的语法以及如何执行我的功能。我的第一个想法是做类似下面代码的事情,但我不确定该怎么做:

if status.ubiquitousItemDownloadingStatus == ???? { function() }

如有任何建议,我们将不胜感激。

谢谢。

status.ubiquitousItemDownloadingStatus的值为URLUbiquitousItemDownloadingStatus。这具有三个值。 .current 表示文件是最新的。

if status.ubiquitousItemDownloadingStatus == .current {
    // it's up-to-date
}

您还可以通过NSMetadataQuery 通知监控下载状态。

let query = NSMetadataQuery()
query.predicate = NSPredicate(format: "%K == %@", NSMetadataItemPathKey, documentsPath) // create predicate to search for you files

NotificationCenter.default.addObserver(forName: .NSMetadataQueryDidUpdate, object: query, queue: nil) { notification in
  for i in 0..<query.resultsCount {
    if let item = query.result(at: i) as? NSMetadataItem {
      let downloadingStatus = item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as! String
      print(downloadingStatus)

      if downloadingStatus == URLUbiquitousItemDownloadingStatus.current.rawValue {
        // file is donwloaded, call your function
      }
    }
  }
}

query.start() // starts the search query, updates will come through notifications

// Once we are listening for download updates we can start the downloading process
try? FileManager.default.startDownloadingUbiquitousItem(at: documentsPath)