Cri*_*sei 1 nsfilemanager icloud swift
我正在尝试在我的应用程序的 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)") }
}
Run Code Online (Sandbox Code Playgroud)
控制台打印:
URLResourceValues(_values: [__C.NSURLResourceKey(_rawValue: NSURLUbiquitousItemDownloadingStatusKey): NSURLUbiquitousItemDownloadingStatusCurrent], _keys: 设置([__C.NSURLResourceKey(_rawValue: NSURLUbiquitousItemDownloadingStatusKey)]))
我感到困惑的是 NSMetadata 的语法以及如何执行我的函数。我的第一个想法是做类似下面代码的事情,但我不知道如何去做:
if status.ubiquitousItemDownloadingStatus == ???? { function() }
Run Code Online (Sandbox Code Playgroud)
任何建议,将不胜感激。
谢谢。
您还可以通过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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
696 次 |
| 最近记录: |