我有以下删除文件的功能(恰好是 iCloud)。有时它有效,有时它挂在 filecoordinate.coordinate 行:
func deleteDocumentAtURL(url: NSURL) {
print("IN DELETE: existing url: \(url)")
print("IN DELETE: openable: \(itemIsOpenable(url as URL))")
let fileCoordinator = NSFileCoordinator(filePresenter: nil)
print("IN DELETE: attempting file coordinator, might get STUCK here")
print("IN DELETE: file coordinator = \(fileCoordinator)")
var fileError: NSError?
fileCoordinator.coordinate(writingItemAt: url as URL, options: .forDeleting, error: &fileError, byAccessor: { (urlForModifying) -> Void in
print("IN DELETE: modifying URL: \(urlForModifying)")
do {
print("IN DELETE deleteDocumentBlock")
try FileManager.default.removeItem(at: urlForModifying)
print("IN DELETE: deletion OK")
} catch let error as NSError {
let alert = UIAlertController(title: "Error deleting", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
})
print("Error code = \(fileError)")
print("IN DELETE: at the end")
}
itemIsOpenable 函数检查 iCloud 下载状态如下:
func itemIsOpenable(_ url:URL?) -> Bool {
// Return false if item is nil
guard let itemURL = url else {
return false
}
// Return true if we don't have access to iCloud (which means
// that it's not possible for it to be in conflict - we'll always have
// the latest copy)
if DocumentListViewController.iCloudAvailable == false {
return true
}
// Ask the system for the download status
var downloadStatus : AnyObject?
do {
try (itemURL as NSURL).getResourceValue(&downloadStatus,
forKey: URLResourceKey.ubiquitousItemDownloadingStatusKey)
} catch let error as NSError {
NSLog("Failed to get downloading status for \(itemURL): \(error)")
// If we can't get that, we can't open it
return false
}
print("item is openable download status = \(downloadStatus)")
// Return true if this file is the most current version
if downloadStatus as? String == URLUbiquitousItemDownloadingStatus.current.rawValue {
print("download status = \(downloadStatus)")
return true
} else {
let currentStatus = downloadStatus as? String
print("current status = \(currentStatus)")
print("Ubiq status = \(URLUbiquitousItemDownloadingStatus.current.rawValue)")
return false
}
}
应用挂起时的打印输出如下(不再赘述):
在删除:现有网址:file:///private/var/mobile/Library/Mobile%20Documents/iCloud~net~thesavorys~Notes/Documents/Document%201997293854.note
项目是可打开的下载状态=可选(NSURLUbiquitousItemDownloadingStatusCurrent)下载状态=可选(NSURLUbiquitousItemDownloadingStatusCurrent)IN DELETE:openable:true IN DELETE:尝试文件协调器,可能会卡在这里IN DELETE:文件协调器= NSFileCoordinator:0x17046de40
任何关于这里发生的事情的想法都非常感谢......
谢谢蒂姆