[英]Completion closure in swift doesn't appear to be firing
我正在關注O'reilly的“Learning Swift”一書,我有一些代碼如下:
func deleteDocumentAtURL(url: NSURL) {
NSLog("Got to top of deleteDocumentAtURL, url: \(url)")
let fileCoordinator = NSFileCoordinator(filePresenter: nil)
fileCoordinator.coordinateWritingItemAtURL(url, options: .ForDeleting, error: nil, byAccessor: { (urlForModifying) -> Void in
NSLog("Here I am")
do {
NSLog("Got inside deleteDocumentBlock")
try NSFileManager.defaultManager().removeItemAtURL(urlForModifying)
// Remove the URL from the list
self.availableFiles = self.availableFiles.filter {
$0 != url
}
// Update the collection
self.collectionView?.reloadData()
} 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.presentViewController(alert, animated: true, completion: nil)
}
})
}
當我運行此代碼(通過單擊界面中的按鈕觸發)時,應用程序將掛起。 另外,do {}內的日志沒有觸發,這讓我覺得整個塊都有問題? 幫助贊賞。
因為
let fileCoordinator = NSFileCoordinator(filePresenter: nil)
在函數中是本地的。 如果您完成了該功能,則該變量已被銷毀。 因此,無法執行異步塊。
將fileCoordinator作為實例變量放到類中。
您沒有處理錯誤,可能有錯誤
coordinateReadingItemAtURL的文檔 :
outError:輸入時,指向錯誤對象指針的指針。 如果文件演示者在准備此讀取操作時遇到錯誤,
在此參數中返回該錯誤,並且不執行reader參數中的塊。
如果在執行讀取器塊之前取消此操作,則此參數在輸出時包含錯誤對象。
添加錯誤處理程序,看看是否收到錯誤
func deleteDocumentAtURL(url: NSURL) {
NSLog("Got to top of deleteDocumentAtURL, url: \(url)")
let fileCoordinator = NSFileCoordinator(filePresenter: nil)
var error: NSError?
fileCoordinator.coordinateWritingItemAtURL(url, options: .ForDeleting, error: &error, byAccessor: { (urlForModifying) -> Void in
NSLog("Here I am")
do {
NSLog("Got inside deleteDocumentBlock")
try NSFileManager.defaultManager().removeItemAtURL(urlForModifying)
// Remove the URL from the list
self.availableFiles = self.availableFiles.filter {
$0 != url
}
// Update the collection
self.collectionView?.reloadData()
} 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.presentViewController(alert, animated: true, completion: nil)
}
})
//Error:
if(error != nil){
print(error)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.