繁体   English   中英

在Swift中使用NSFileManager删除文件时无法获得完成结果

[英]Cannot get completion result when removing file using NSFileManager in Swift

我正在尝试删除用户录制的视频,现在决定删除。 我既有文件URL,又有路径。

我已经尝试过使用NSFileManager类的删除方法来NSFileManager文件和路径,但是在获取完成结果以确认文件是否确实被删除时遇到了麻烦。

这是我尝试在Swift中删除文件的示例:

let deleted = try! NSFileManager.defaultManager().removeItemAtURL(self.fileURL)

这将给我一个警告,提示Constant 'deleted' inferred to have type '()', which may be unexpected

使用removeItemAtPath会产生相同的警告。 如果我运行代码,则deleted仅记录为()

如果我查看这两个方法的方法签名,很明显它们没有返回结果,但是以removeItemAtURL方法的文档为例: true if the item was removed successfully or if URL was nil. Returns false if an error occurred. If the delegate aborts the operation for a file, this method returns true. However, if the delegate aborts the operation for a directory, this method returns false. true if the item was removed successfully or if URL was nil. Returns false if an error occurred. If the delegate aborts the operation for a file, this method returns true. However, if the delegate aborts the operation for a directory, this method returns false.

它还提到采用error参数,但没有参数。 最后在最后一句话中说: Returns YES if the item was removed successfully or if URL was nil.

作为最后的选择,我认为我可以成为NSFileManager ,但是它的委托人协议没有提供任何完成方法。

如何正确删除文件或路径,然后验证它实际上已被删除?

没错,在Swift中它会返回Void (我相信文档中包含了打开Objective-C或Both时的返回值说明,与Swift相对的是,它们需要做很多工作才能进行更新文档)。

如果继续阅读该函数的文档,您将看到标题为“在Swift中处理错误”的部分,其中说:

在Swift中,此方法返回Void并用throws关键字标记,以指示在失败的情况下抛出错误。

您可以在try表达式中调用此方法,并处理do语句的catch子句中的任何错误,如Swift编程语言(Swift 2.1)中的错误处理和结合使用Swift与Cocoa和Objective-C(Swift 2.1)中的错误处理中所述)。

因此,将您的呼叫包裹在try/catch ,如果有错误,则处理该错误。 如果没有错误,则说明成功。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM