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

Cannot get completion result when removing file using NSFileManager in Swift

我正在尝试删除用户录制的视频,现在已决定删除。我有一个文件 URL,显然还有一个路径。

我已经尝试使用 NSFileManager class 的删除方法来删除文件和路径,但是我无法获得完成结果来确认文件是否真的被删除了删不删

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

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

这会给我一个 Constant 'deleted' inferred to have type '()', which may be unexpected

的警告

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

如果我查看这两种方法的方法签名,很明显它们不会 return 结果,但以 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.

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

作为最后的手段,我想我可以成为 NSFileManager 的委托,但它的委托协议不提供任何完成方法。

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

你是对的,在 Swift 中 returns Void(我相信文档包含 return 值描述,当你有 Objective-C 或两者都打开,而不仅仅是 Swift -- 他们有很多工作要做更新文档)。

如果您继续阅读该函数的文档,您将看到一个标题为 "Handling Errors in Swift" 的部分,其中说:

In Swift, this method returns Void and is marked with the throws keyword to indicate that it throws an error in cases of failure.

You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 2.1) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 2.1).

因此,请将您的调用包装在 try/catch 中,并在出现错误时进行处理。如果没有错误,它就成功了。