Как читать данные из текстового файла iOS 15

Обновление: этот код работает в симуляторе, но не на моем устройстве. Очевидно, мне нужно, чтобы он работал на обоих.

Я следовал инструкциям, но не могу заставить эту функцию работать. Когда пользователь выбирает элемент barButtonItem, открывается DocumentPicker, позволяя пользователю выбрать файл .txt. Затем я беру URL-адрес выбранного файла и пытаюсь вернуть из него строку; однако я получаю следующую ошибку: «Не удалось открыть файл «Test.txt», поскольку у вас нет разрешения на его просмотр». Что мне не хватает? Я где-то не спросил разрешения? Пробовал чистить папку сборки - не помогло.

      @IBAction func importFileBtnTapped(_ sender: Any) {
        selectFiles()
    }
    
    
    func selectFiles() {
        let types = UTType.types(tag: "txt",
                                 tagClass: UTTagClass.filenameExtension,
                                 conformingTo: nil)
        let documentPickerController = UIDocumentPickerViewController(forOpeningContentTypes: types)
        documentPickerController.delegate = self
        self.present(documentPickerController, animated: true, completion: nil)
    }
    
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let myURL = urls.first else {
            let alert = SCLAlertView()
            alert.showError("ERROR", subTitle: "Unable to retrieve document.")
            return
        }
        let text = createStringFromSelectedFile(fileURL: myURL)
        if text == "error" {
            print("ERROR creating a string from the selected file.")
            return
        }
        let separatedStrings = decipherString(text: text)
        if separatedStrings.first == "error" {
            print("ERROR deciphering the string in ClaimInfoViewController")
            return
        }
        for string in separatedStrings {
            print("\(string)")
        }
        print("import result: \(myURL)")
    }
    
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        dismiss(animated: true, completion: nil)
    }
    
    
    func createStringFromSelectedFile(fileURL: URL) -> String {
        var text = String()
        do {
            text = try String(contentsOf: fileURL)
        }
        catch {
            print("ERROR in the createStringFromSelectedFile function in ClaimInfoViewController")
            print("The error: \(error.localizedDescription)")
            let alert = SCLAlertView()
            alert.showError("ERROR", subTitle: "Unable to read the file. Please try again.")
            return "error"
        }
        return text
    }
    
    func decipherString(text: String) -> [String]{
        let newText = text
        let startIndexes = ["<Claim#",
                            "<File#",
                            "<DateOfLoss:"
        ]
        var claimNumber = String()
        var fileNumber = String()
        var dateOfLoss = String()
        
        for indexValue in startIndexes {
            guard let index = newText.firstIndex(of: ">") else { return ["error"] }
            let newString = String(newText[..<index])
            
            if indexValue == "<Claim#" {
                claimNumber = newString
            }
            else if indexValue == "<File#" {
                fileNumber = newString
            }
            else if indexValue == "<DateOfLoss:" {
                dateOfLoss = newString
            }
        }
        
        let finalText = [claimNumber, fileNumber, dateOfLoss]
        
        return finalText
    }

1 ответ

Благодаря Мэтту, который прокомментировал выше, я смог выяснить, что это проблема безопасности. Добавление этого простого кода решило проблему:

      let shouldStopAccessing = pickedFolderURL.startAccessingSecurityScopedResource()
        defer {
          if shouldStopAccessing {
            pickedFolderURL.stopAccessingSecurityScopedResource()
          }
       }

Я добавил его прямо перед этой строкой кода, которую можно увидеть выше:

      let text = createStringFromSelectedFile(fileURL: myURL)

Я получил этот код отсюда: StackOverflow Post

Другие вопросы по тегам