swift - 我的 CompletionHandler 不会执行。为什么?
问题描述
我有以下代码:
document?.open { success in
if success {
print("file opened")
self.consumed = self.document?.consumed
} else {
print("file read failure")
}
}
可以看出,我有一个成功和失败的打印。但都没有打印。
合理的问题是文件不存在,不可读或其他东西。因此,我在此代码之前添加了以下内容:
if document != nil {
print("not nil")
let asString = document?.fileURL.path
let toast = FileManager.default.fileExists(atPath: asString!)
if toast {
print("file exist")
} else {
print("file does not exist")
}
} else {
print("nil")
}
if FileManager.default.isReadableFile(atPath: (document?.fileURL.path)!)
{
print("readable")
}
else
{
print("not readable")
}
这对我来说表明它是:不为零,存在且可读。
有时我会错过不执行此完成代码吗?能够打开文件会很棒,但我认为它没有运行的事实是第一步。
关于文件的注意事项。它是从包中读取并复制到 Documents 目录的文件。我查看了文件的属性,并没有发现任何奇怪的地方。
解决方案
尝试替换document?.open
为document!.open
,或使用保护让真正确保文档不为零。因为如果document
为 nil 则整个调用被跳过。
在这里你可以阅读可选链。
推荐阅读
- python - Python lxml soupparser 失败并出现“无效的 PI 名称”
- android - Leanback ListRow 在屏幕中心滚动
- java - 如何从图像列表中制作视频?
- reactjs - 将 React 16 应用程序升级到 Apollo 2 问题
- tfs - 如何在 TFS 中重命名多个标签
- c - 如何读取在预期浮点数末尾错误输入的字符?
- python - Python,Pandas:如何更改 DataFrame.plt.density() 的带宽选择?
- java - 如何对自身进行递归回溯?
- visual-studio-code - 我可以根据文件类型设置 VS Code 默认 EOL 吗?
- weather-api - 是否有过去 NOAA 天气预报的 API(预报档案)?