来自UIDocumentPIckerViewController的PDF出现在文档目录中,但不出现在Bundle

时间:2017-12-31 20:33:29

标签: swift pdf bundle uidocumentpickerviewcontroller

在下面的代码中,我从UIDocumentPickerViewController中获取PDF并将其放入文档目录中:

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,我的捆绑检查是否也应该说它也在那里?

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

谢谢,

0 个答案:

没有答案