【问题标题】:UIDocumentPickerViewController allows selecting a file the first time the app is run, but not subsequentlyUIDocumentPickerViewController 允许在应用程序第一次运行时选择文件,但随后不能
【发布时间】:2018-08-19 12:36:24
【问题描述】:

我的应用程序在运行时会在其文档目录中创建一个 json 文档(使用 UIDocument 子类)。然后,当打开 UIDocumentPickerViewController 选择文件时,如果应用程序写入了新文件,则行为符合预期。

但是,如果我再次运行应用程序(并覆盖上次创建的文件),则不会调用委托方法 didPickDocumentsAt,除非我浏览几秒钟。

我在这里错过了什么?

@IBAction func showDocumentPicker() {
    let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeJSON as String], in: .import)
    documentPicker.allowsMultipleSelection = false
    documentPicker.delegate = self
    self.present(documentPicker, animated: true, completion: nil)
} //this function is in the initial definition of the class and is connected to a UIBarButton


extension BudgetExportViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print("selected document: \(urls.first)")
        print("555555555555555555555555555555")
        //document = BudgetExportDocument(fileURL: urls.first!)
//                CFURLStartAccessingSecurityScopedResource(urls.first! as CFURL)
//                let documentData = try? Data.init(contentsOf: urls.first!)
//                let json = try? JSONDecoder().decode(BudgetExportData.self, from: documentData!)
//                budgetThisMonth = json
//                print("Budgetthismonth")
//                print(budgetThisMonth)
//                CFURLStopAccessingSecurityScopedResource(urls.first! as CFURL)
    }
}

【问题讨论】:

  • 你不需要将选择器分配给一个属性,这样它就不会被释放吗?我想知道它是否有足够的时间在它被释放之前调用它的委托。
  • 它现在正在工作,并且每次都会调用它的委托方法。我猜它不会被释放,但我只尝试了 10 秒浏览选择器的顶部(并且最小值是在加载视图控制器后要选择的文件已经在屏幕上时)。尽管如此,我还是不明白为什么覆盖一个文件会导致它在几秒钟内没有调用它的委托方法。如果我将来遇到这个问题,我会把它变成一个属性。感谢您的建议!

标签: swift swift4.1 uidocumentpickerviewcontroller


【解决方案1】:

显然,问题在于我多次覆盖同一个文件。现在,如果存在同名文件,它不会覆盖它,并且 UIDocumentPickerViewController 的行为符合预期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多