如何使用UIDocumentPicker将pdf文件导入表视图单元格

时间:2018-04-16 05:59:00

标签: ios swift xcode pdf uidocument

我真的被困在如何导入pdf文件并将其存储在表格视图单元格中。我正在使用UIDocumentPicker导入pdf文件,但我无法弄清楚如何将pdf文件数据存储到表视图单元格。我的问题是我创建了一个名为insertNewFileTitle()的函数,每次单击addButtonTapped函数时都会附加一个新的表视图单元格。我想确保pdf数据仍然在我导入pdf文件的正确表视图单元格中。

我想要做的是让表格视图单元格存储导入的pdf文件,以便稍后我可以在选择表格单元格时将pdf文件作为邮件编辑器的附件发送。非常感谢,谢谢。

var pdfFiles: [String] = []
var myPDFsArray : Array<MyPDFs> = []
var selectedRow : NSInteger? // optional NSInteger

@available(iOS 8.0, *)
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {

    let myURL = url as URL
    print("import result : \(myURL)")

    do {
        let data = try Data(contentsOf: myURL)
        print("data=\(data)")

    }
    catch {/* error handling here */}

    let pathString = myURL.path // String path for PDF
    let PDFName = myURL.lastPathComponent // string for PDF Name

    if controller.documentPickerMode == UIDocumentPickerMode.import {
        DispatchQueue.main.async(){
            self.myPDFsArray.append(MyPDFs(fileTitle: pathString, fileName: PDFName))

            }
    }
    print (pathString)
    print (PDFName)
}

@available(iOS 8.0, *)
public func documentMenu(_ documentMenu:UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
    documentPicker.delegate = self
    present(documentPicker, animated: true, completion: nil)
    //self.present(documentPicker, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    print("we cancelled")

    dismiss(animated: true, completion: nil)
}

func documentMenuWasCancelled(documentMenu: UIDocumentMenuViewController) {
    print("menu got cancelled")
    documentMenu.dismiss(animated: true, completion: nil)

}

@IBAction func addButtonTapped(_ sender: Any){
    let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)
    importMenu.delegate = self
    importMenu.modalPresentationStyle = .formSheet
    self.present(importMenu, animated: true, completion: nil)
    //importMenu.addOption(withTitle: "Create New Document", image: nil, order: .first, handler: {print("New Doc Requested")})
    insertNewFileTitle()
}

func insertNewFileTitle(){
    if addFileTextField.text!.isEmpty {
        print("Add Video Text Field is empty")
    }
    pdfFiles.append(addFileTextField.text!)

    let indexPath = IndexPath(row: pdfFiles.count - 1, section: 0)
    tableView.beginUpdates()
    tableView.insertRows(at: [indexPath], with: .automatic) //can customize
    tableView.reloadData()//reload table
    tableView.endUpdates()
    addFileTextField.text = ""
    view.endEditing(true)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return pdfFiles.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let fileTitleCell = pdfFiles[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell") as! FileCell
    cell.fileTitle.text = fileTitleCell

    if myPDFsArray.contains(MyPDFs(fileTitle: "fileTitle", fileName: "fileName")){

        cell.accessoryType = .checkmark
    }

    else{
        cell.accessoryType = .none
    }
    return cell
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedRow = indexPath.row // indexPath.row is the value of the row you tap on, starting from first 0
    tableView.deselectRow(at: indexPath, animated: true)
    if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
        //selectedRow = indexPath.row // indexPath.row is the value of the row you tap on, starting from first 0
        //if myPDFsArray.contains(MyPDFs(fileTitle: "fileTitle", fileName: "fileName")){
        if cell.accessoryType == .checkmark{
            cell.accessoryType = .none
            //myPDFsArray.remove(at: MyPDFs.index(ofAccessibilityElement: NSObject.self))

            //print(MyPDFs.init(fileTitle: "fileTitle", fileName: "fileName"))
            print("")
            print(myPDFsArray[indexPath.row].fileTitle!)
            print("")
            print(myPDFsArray[indexPath.row].fileName!)
        }
        else{
            cell.accessoryType = .checkmark
            selectedRow = indexPath.row
            myPDFsArray.append(MyPDFs(fileTitle: "fileTitle", fileName: "fileName"))
            //print(MyPDFs.init(fileTitle: "fileTitle", fileName: "fileName"))
            print("")
            print(myPDFsArray[selectedRow!].fileTitle!)
            print("")
            print(myPDFsArray[selectedRow!].fileName!)
        }
        //}
    }
}

下一部分是我发送电子邮件的按钮操作

@IBAction func sendEmail(_sender: Any) {     
    let subject = "subject"
    let messageBody = "pdf file names"
    lblValidationMessage.isHidden = true

    let allPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = allPaths.first!
    let myPath = "/(MyPDFs[selectedRow].fileName)" //is it a forward slash or backslash? 
    let pathForFile = documentsDirectory.appending(myPath)
    print("")
    print(pathForFile)
    print("")

    guard let email = emailNew.text, emailNew.text?.characters.count != 0  else {
        lblValidationMessage.isHidden = false
        lblValidationMessage.text = "Please enter your email"
        return
    }

    if isValidEmail(emailNew: email) == false {
        lblValidationMessage.isHidden = false
        lblValidationMessage.text = "Please enter a valid email address"
        return
    }

    if( MFMailComposeViewController.canSendMail() ) {
        print("Can send email.")

        let mailComposer = MFMailComposeViewController()
        mailComposer.mailComposeDelegate = self

        //Set the subject and message of the email
        mailComposer.setToRecipients([email])
        mailComposer.setSubject(subject)
        mailComposer.setMessageBody(messageBody, isHTML: false)


        // Add attachment
        if let fileData = NSData(contentsOfFile: pathForFile) {
            print("file data loaded")
                mailComposer.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "fileName")
            }

        //this will compose and present mail to user"
        self.present(mailComposer, animated: true, completion: nil)
     }
    else {
        self.showSendMailErrorAlert()
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确理解这一点。为什么需要将PDF存储在UITableView单元格中?

为什么不创建这样的模型:

class MyPDFs : NSObject
{
    var fileTitle : String?
    var fileName : String?

    override init(){}

    convenience init(fileTitle : String , fileName : String)
    {
        self.init()

        self.fileTitle = fileTitle
        self.fileName  = fileName
    }
}

每次点击addButton,创建一个新对象,将其附加到MyPDFs类型的数组,然后重新加载表。

var myPDFsArray : Array<MyPDFs> = []
myPDFsArray.append(MyPDFsObject)
myUITableView.reloadData()

这样,当您使用indexPath.row选择UITableView单元格时,您可以获取PDF属性,并且可以获取附加到MailComposer的名称和文件路径。

相关问题