0

在下面的代码中,我从 UIDocumentPickerViewController 中获取了一个 PDF 并将其放入 Document Directory 中:

do {
        //1 Get the data from the url of Announcements.pdf
        let urlData = try NSData(contentsOf: url, options: NSData.ReadingOptions()) 
        print (urlData) //The data appears in the console

        //2 Write the data of Announcements.pdf to the Document Directory
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = "\(documentsPath)/Announcements.pdf"
         urlData.write(toFile: filePath, atomically: true)


        3 // List files in document directory. Announcements.pdf appears in the directory.

        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            print ("The document directory contains:\(fileURLs)")
        } catch {
            print("Error while enumerating files : \(error.localizedDescription)")
        }

     4 // Double check to make sure the file exists. It does.

    documentsDirectory = FileManager.default.urls(for:  .documentDirectory, in: .userDomainMask).last! as NSURL
    //documentsDirectory == /var/mobile/Containers/Data/Application/81B3AB80-1057-4EB9-AA04-0CC9F2FA3981/Documents

    //File Path is /var/mobile/Containers/Data/Application/81B3AB80-1057-4EB9-AA04-0CC9F2FA3981/Documents/Announcements.pdf

    fileURL = documentsDirectory!.appendingPathComponent(url.lastPathComponent) as NSURL?

    print ("Before we check, fileURL is \(String(describing:fileURL))")

    //This shows: Optional(file:///var/mobile/Containers/Data/Application/81B3AB80-1057-4EB9-AA04-0CC9F2FA3981/Documents/Announcements.pdf)

    if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
        print("File exists. Its URL is \(String(describing: fileURL))")
        finalFilePath = fileURL! as URL
        filename = fileURL!.lastPathComponent!
        print ("The filename is \(filename)")
        books.append(filename)
        tableView.reloadData()
        fileIsFromService = true
    }

    else{
        print("File does not exist")
    }

}

但是当我在下面的代码中检查 Bundle for Announcements.pdf 时,它不存在:

       print (Bundle.main.url(forResource: "Announcements", withExtension: "pdf")) //this nil

    guard let finalFilePath = Bundle.main.url(forResource: "Announcements", withExtension: "pdf")

        else

    {
        print ("Guard statement failed")
        return }

如果 Announcements.pdf 出现在文档目录中,我的捆绑检查不应该说它也在那里吗?

如果没有,我做错了什么?

谢谢,

伊莱

4

0 回答 0