我正在使用FileManager编辑、移动和删除我的应用程序中的文件。但是如何确保moveItem方法已经完成呢?有没有可能的回调?我读到了一些关于FileManagerDelegate的东西,但我没有找到足够的信息来使用它。谢谢
发布于 2018-07-31 17:17:18
moveItem(at:to:)方法是同步的,这意味着在操作完成之前,它不会转移到任何代码行。在Swift中,它也是throws,所以如果它给你一个错误,你就知道出了问题,如果它继续前进,一切都会好起来的。你应该这样称呼它:
do{
try FileManager.default.moveItem(at: origURL, to: newURL)
}
catch let error{
// Handle any errors here
dump(error)
}在Objective-C中,它返回一个指定操作是否成功的BOOL,并接受一个引用传递NSError,如果出现错误,它将对其进行配置。例如:
NSError *error = nil;
BOOL success = [[NSFileManager defaultManager] moveItemAtURL:origURL toURL:newURL error:&error];
if(!success || error){
// Something went wrong, handle the error here
}
else{
// Everything succeeded
}发布于 2018-07-31 17:31:10
为了更方便起见,您可以扩展您的FileManager以添加一些方法:
extension FileManager {
func moveItem(at url: URL, toUrl: URL, completion: @escaping (Bool, Error?) -> ()) {
DispatchQueue.global(qos: .utility).async {
do {
try self.moveItem(at: url, to: toUrl)
} catch {
// Pass false and error to completion when fails
DispatchQueue.main.async {
completion(false, error)
}
}
// Pass true to completion when succeeds
DispatchQueue.main.async {
completion(true, nil)
}
}
}
}然后这样叫它:
FileManager.default.moveItem(at: atUrl, toUrl: toUrl) { (succeeded, error) in
if succeeded {
// Success
} else {
// Something went wrong
}
}https://stackoverflow.com/questions/51609251
复制相似问题