首页 > 解决方案 > 我的 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 目录的文件。我查看了文件的属性,并没有发现任何奇怪的地方。

标签: swiftuidocument

解决方案


尝试替换document?.opendocument!.open,或使用保护让真正确保文档不为零。因为如果document为 nil 则整个调用被跳过。

在这里你可以阅读可选链。


推荐阅读