Reading file inside documentPicker returns nil

619 views Asked by At

I am reading a plist file selected by the user in iOS swift. The code works as expected on XCode simulators (iPhone 13). But on a real iPhone 13, the readArrayFromPlist function returns nil. I couldn’t find the reason.

  • I've selected the file using document picker both from my iPhone and iCloud.
  • I've read that iOS provides permission inside documentPicker function.
  • I've printed the URL and it looks OK (+ it works on simulators).

Here is the code (imagePosArray is nil on real iPhone):

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    guard let myURL = urls.first else {
        return
    }
    print("import result : \(myURL)")
    imagePosArray = readArrayFromPlist(filepath: myURL.path)
}

func readArrayFromPlist(filepath: String) -> [Int]? {
    if let arrayFromFile: [Int] = NSArray(contentsOfFile: filepath) as? [Int] {
        return arrayFromFile
    }
    return nil
}
1

There are 1 answers

0
user3157047 On

I found the issue and solved it. I should have used didPickDocumentAt instead of didPickDocumentsAt and then request access. Here is the new code:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    // Start accessing a security-scoped resource.
    guard url.startAccessingSecurityScopedResource() else {
        // Handle the failure here.
        return
    }

    print(url.path)
    imagePosArray = readArrayFromPlist(filepath: url.path)

    // Make sure you release the security-scoped resource when you finish.
    defer { url.stopAccessingSecurityScopedResource() }
}