swiftfile-browser

Couldn't get files contents on a real device (swift file base app)


I have a file based app that opens source code. Here is the function that I use for it.

func presentDocument(at documentURL: URL) {
    
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let documentViewNavController = storyBoard.instantiateViewController(withIdentifier: "documentNavVc")
    
    do {
        
        let text =  try String(contentsOf: documentURL, encoding: .utf8)
        let name = documentURL.lastPathComponent
        if let documentViewController = documentViewNavController.contents as? DocumentViewController{
            documentViewController.text = text
            documentViewController.title = name
        }
        
    }
    catch {
        print(error.localizedDescription)
    }
    
    documentViewNavController.modalPresentationStyle = .fullScreen
    
    present(documentViewNavController, animated: true, completion: nil)
}

}

so the issue is that on a simulator it works perfectly, but on a real device, it gets to catch block after it tries to get contents of the file and prints this error: The file couldn’t be opened because you don’t have permission to view it.

Maybe its because I don't ask the permission of the user to use the file browser (I don't know)

Any solution here?


Solution

  • So the solution was to open secured files (all files, except ones you have in your app folder are secured) and this article helped me https://developer.apple.com/documentation/uikit/view_controllers/providing_access_to_directories