swift 当ubiquitousItemDownloadingStatusKey为“当前”时,我正在尝试运行函数

k3fezbri  于 2022-12-28  发布在  Swift
关注(0)|答案(2)|浏览(141)

我正在尝试下载应用的iCloud ubiquity容器中的目录,我希望在下载完成后调用函数。我可以获得如下状态:

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)") }
}

控制台打印:
URL资源值(_values:[__C. NSURL资源密钥(_原始值:基本项目下载状态键):NSURLUbiquitousItemDownloading状态当前],_密钥:设置([__C. NSURL资源密钥(_原始值:NSURL基本项目下载状态键)]))
让我困惑的是NSMetadata的语法和如何执行我的函数。我的第一个想法是做一些类似下面的代码,但我不知道如何去做:

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

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

7fyelxc5

7fyelxc51#

您还可以通过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.resultCount {
    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)
58wvjzkj

58wvjzkj2#

status.ubiquitousItemDownloadingStatus的值是URLUbiquitousItemDownloadingStatus,它有三个值,.current表示文件是最新的。

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

相关问题