如何在SwiftUI中使用文件导入器选择文件?

dgtucam1  于 2023-06-21  发布在  Swift
关注(0)|答案(2)|浏览(177)

我想在SwiftUI中的FileImporter中选择文件,但无法选择文件

这是我的代码:

struct ContentView: View {

@State var isShowing = false

var body: some View {
    
    VStack {
        Button {
            isShowing.toggle()
        } label: {
            Text("documents")
        }.fileImporter(isPresented: $isShowing, allowedContentTypes: [.item]) { result in
            
            switch result {
            case .success(let Fileurl):
                print(Fileurl)
            case .failure(let error):
                print(error)
            }     
        }
    }  
}

我该怎么办?

k97glaaz

k97glaaz1#

更新Xcode 14.2

自Xcode版本14.2以来,此错误已修复,如果使用allowedContentTypes,文件导入器允许选择所有文件:[.item]
最后,可以在模拟器中单击一下选择所有文件。

旧答案-适用于Xcode 14.1或更低版本

经过很长时间的寻找,我找到了这个问题的答案
在模拟器中不可能选择文件,但是如果你需要选择文件来测试你的代码,你可以做这些步骤

**第一步:**暂挂文件
**第二步:**弹出文件后,再次点击

通过这两个步骤,您可以选择您的文件

7vhp5slm

7vhp5slm2#

这里是你要找的:

struct ContentView: View {
    
    @State var isShowing = false
    
    var body: some View {
        
        VStack {
            Button {
                isShowing.toggle()
            } label: {
                Text("documents")
            }
            .fileImporter(isPresented: $isShowing, allowedContentTypes: [.item], allowsMultipleSelection: true, onCompletion: { results in
                
                switch results {
                case .success(let fileurls):
                    print(fileurls.count)
                    
                    for fileurl in fileurls {
                        print(fileurl.path)
                    }
                    
                case .failure(let error):
                    print(error)
                }
                
            })

        }
        
    }
    
}

相关问题