1

I have a Swift application that has UIDocumentPicker implemented for opening .json files from the user's iCloud Drive or local filesystem. As of now, after selecting a file in the DocumentPicker view controller, the URL to the file is printed to console:

import Foundation
import SwiftUI

public struct DocumentPicker : UIViewControllerRepresentable {
    public func makeCoordinator() -> Coordinator {
        return DocumentPicker.Coordinator(parent1: self)
    }
    
    
    public func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) ->
        DocumentPicker.UIViewControllerType {
            let picker = UIDocumentPickerViewController(documentTypes: [String("public.json")], in: .import)
            picker.allowsMultipleSelection = false
            picker.delegate = context.coordinator
            return picker
    }
    
    public func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context:
        UIViewControllerRepresentableContext<DocumentPicker>) {
            // ...
    }
    
    public class Coordinator : NSObject,UIDocumentPickerDelegate {
        var parent : DocumentPicker
        
        init(parent1 : DocumentPicker) {
            parent = parent1
        }
        
        public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            print(urls)
        }
    }
}

As of now, an array (with only 1 URL as .allowsMultipleSelection is temporarily set to false) is printed to console, for example:

[file:///private/var/mobile/Containers/Data/Application/5A23352A-E0A3-4169-BBEF-CBA64A695A61/tmp/com.company.App-Inbox/someFile.json]

I have done quite a bit of research, and I can find loads of tutorials on how to parse data from remote HTTP/S servers that send an application/json response, as well as plenty on how to read from a JSON file bundled with the app in Xcode, but none of these work for reading and parsing data from a file opened using UIDocumentPicker. Documentation is even sparse on how to even use files selected in UIDocumentPicker after "opening" them. I'm super new to Swift so any advice would be appreciated!

drcomputer
  • 406
  • 2
  • 7
  • 15
  • 1
    `Data` has a method to open a file given its URL which you have. From there, serialize the JSON into whatever kind of model object you want. There are lots of examples of both steps on Stack Overflow. – Aaron Brager Jul 14 '20 at 04:27
  • Use `readFileContent(path:)` to read the file. – El Tomato Jul 14 '20 at 04:45
  • Thank you! Turns out that is `Data(contentsOf: url)`. If anyone stumbles across this question in the future, `do { let fileData = try Data(contentsOf: urls[0]) // ... } catch { print("error") }` is how I went about accomplishing this. – drcomputer Jul 14 '20 at 05:09

0 Answers0