Theo Carper
Theo Carper

Reputation: 270

Unable to open a file using .fileImporter on actual device

This use to work when deployed on a real device when I was testing iOS 14 beta, but now in production it only works on the emulator. Did something change in IOS 14? I received the following error:

FilePickerTest[15486:5885508] [AXRuntimeCommon] Unknown client: FilePickerTest

The file “16010282771_20190702_23_38.csv” couldn’t be opened because you don’t have permission to view it.

Is there a setting I need to add to give my app permission to access the file?

import SwiftUI

struct ContentView: View {
    @State private var openFile = false
    @StateObject var doc = ViewModel()
    
    var body: some View {
        VStack {
            Text("Tap to pick a csv file")
                .padding()
                .onTapGesture(perform: {
                    openFile.toggle()
                })
        }
        .fileImporter(isPresented: $openFile, allowedContentTypes: [.commaSeparatedText]) { (res) in
            do {
                let fileUrl = try res.get()
                print(fileUrl)
                doc.viewFile(fileUrl: fileUrl)
            } catch {
                print("Error reading file")
                print(error.localizedDescription)
            }
        }
        
    }
}

import SwiftUI

class ViewModel: ObservableObject {
    
    var readString = ""
    func viewFile(fileUrl: URL) {
        do {
            readString = try String(contentsOf: fileUrl)
        } catch {
            print("Error reading file")
            print(error.localizedDescription)
        }
        
        print("File contents: \(readString)")
    }
}

Upvotes: 4

Views: 2848

Answers (1)

g01dt00th
g01dt00th

Reputation: 101

add fileUrl.startAccessingSecurityScopedResource() before doc.viewFile(fileUrl: fileUrl)

Upvotes: 8

Related Questions