razrabot
razrabot

Reputation: 1

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?

Upvotes: -1

Views: 513

Answers (2)

razrabot
razrabot

Reputation: 1

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

Upvotes: -1

Arhaiziya
Arhaiziya

Reputation: 128

What is the URL you are trying to read from?

For non-jailbreak devices, every application has a sandbox directory (called Document directory) where you can store and read files from only.

To read from added to the project file, you need to ensure it's added to the target and Copy Bundle Resources phase in the build phases. That way the file would be added to the app bundle which will be installed on the device. Then you could access your file simply by its name.

Upvotes: 0

Related Questions