I've been struggling with this for a few days, and hoping someone can point me in the right direction.
I'm using a Document Picker to import a .json file into my app from the Files Directory. On the simulator everything works great, but when testing on a device I keep running into NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." (I've also tried the alternate approach of using .fileImporter, only to get the exact same results.)
I'm probably missing a permission or something? I can't seem to find the right answer online. I do have Supports opening documents in place & Application supports iTunes file sharing in the plist.
Any suggestions would be appreciated.
Here's my code that's mostly cobbled together from tutorials, forums, and anywhere else I could find.
import SwiftUI
import Foundation
import MobileCoreServices
import UniformTypeIdentifiers
struct DocumentPicker: UIViewControllerRepresentable {
func makeCoordinator() -> DocumentPicker.Coordinator {
return DocumentPicker.Coordinator(parent1: self)
}
// Document Picker Setup
func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
let supportedTypes: [UTType] = [UTType.json]
let picker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes)
picker.allowsMultipleSelection = false
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<DocumentPicker>) {
}
class Coordinator: NSObject, UIDocumentPickerDelegate {
var parent: DocumentPicker
init(parent1: DocumentPicker) {
parent = parent1 }
// getting the url for .json
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let archiveurl = urls.first else {
return
}
URLSession.shared.dataTask(with: archiveurl) { data, response, error in
if let data = data {
let jsonDecoder = JSONDecoder()
if let JSONdecoded = try? jsonDecoder.decode(Jproject.self, from: data) {
// using the parsed .json data to populate app info..
self.parseJproject(parsedJSON: JSONdecoded)
}
return
}
}.resume()
}
Three things:
-
I think the key piece you’re missing is the calls to
startAccessingSecurityScopedResource()
andstopAccessingSecurityScopedResource()
. -
Using
URLSession
to access file system resources is… well… it works, but it’s weird.Data.init(contentsOf:options:)
is much easier (-: -
I’d like to plug WWDC 2017 Session 229 Building Great Document-based Apps in iOS 11, which is my go-to reference for this sort of thing.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"