【问题标题】:SwiftUI .fileImporter cannot show again after dismissing by swipe downSwiftUI .fileImporter 在通过向下滑动关闭后无法再次显示
【发布时间】:2021-10-18 09:23:11
【问题描述】:

我在 SwiftUI 中使用 .fileImporter 修饰符在我的应用程序中导入 pdf 文件。我有几个问题。首先,数据加载速度很慢,并且经常无法加载并给出消息内部错误无法与帮助应用程序通信。

但主要问题是,如果模式视图通过向下滑动关闭,则无法再次呈现。大概是因为绑定 $showFileImporter 没有重置。如果按下取消按钮以将其关闭,则它可以正常工作。我不知道是否有强制它全屏来解决这个问题。

这是我的代码:

.fileImporter(isPresented: $showFileImporter, allowedContentTypes: [.pdf]) { result in
        switch result {
        case .success(let url):
            url.startAccessingSecurityScopedResource()
            if let pDFDocument = PDFDocument(url: url) {
                if let data = pDFDocument.dataRepresentation() {
                    // handle data
                    
                }
            }
        case .failure(let error):
            print(error)
        }
    }

【问题讨论】:

    标签: ios xcode swiftui swiftui-fileimporter


    【解决方案1】:

    我可以确认我的 .fileImporter 也不会在向下滑动时重置 isPresented 绑定。可以确定的一种方法是将显示文件导入器的按钮从$showFileImporter = true 更改为$showFileImporter.toggle()。在滑动关闭文件导入器时,您必须按两次按钮才能再次呈现。

    不幸的是,这似乎是另一个半生不熟的 SwiftUI 事情,但我确实找到了一个合适的解决方法 - 使用演示按钮本身来处理这种情况:

    Button(action: {
    if showFileImporter {
        // NOTE: Fixes broken fileimporter sheet not resetting on swipedown
        showFileImporter = false
        DispatchQueue.main.asyncAfter(deadline: .now()+0.2, execute: {
            showFileImporter = true
        })
    } else {
        showFileImporter = true
    }
    }, label: { ... })
    

    我尝试连续调用 .toggle() 两次,但需要稍微延迟触发器才能注册。

    编辑: 我还注意到你没有打电话给url.stopAccessingSecurityScopedResource(),你应该在打电话给你的pDFDocument之后这样做。

    【讨论】:

    • 这是一种临时解决方法。并添加了 stopAccessingSecurityScopedResource()。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多