I am really stuck on how to import a pdf file and store it in a table view cell. I am using the UIDocumentPicker to import the pdf file but I am having trouble figuring out on how to store the pdf files data to a table view cell. My issue is that I have created a function called insertNewFileTitle() that appends a new table view cell every time I click the addButtonTapped function. I want to make sure that the pdf data is still in the correct table view cell from where i imported the pdf file.
What im trying to do is have table view cells store the imported pdf file so then later on i can send the pdf file as an attachment for the mail composer when the table cell is selected. Any insight is appreciated, thank you.
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!)
}
//}
}
}
This next part is my button action to send the email
@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()
}
}