OfflineAssessmentViewController.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. //
  2. // OfflineAssessmentViewController.swift
  3. // LMS
  4. //
  5. // Created by Suraj Kumar Mandal on 11/01/23.
  6. //
  7. import UIKit
  8. import Toast_Swift
  9. import SideMenu
  10. import MobileCoreServices
  11. import UniformTypeIdentifiers
  12. class OfflineAssessmentViewController: UIViewController {
  13. @IBOutlet var downloadView: UIView!
  14. @IBOutlet var downloadImageView: UIImageView!
  15. @IBOutlet var downloadLabel: UILabel!
  16. @IBOutlet var uploadView: UIView!
  17. @IBOutlet var uploadImageView: UIImageView!
  18. @IBOutlet var uploadLabel: UILabel!
  19. var viewModel = OfflineAssessmentViewModel()
  20. let userData = DBManager.sharedInstance.database.objects(UserDetailsModel.self)
  21. var assessmentName = String()
  22. var assessmentId = Int()
  23. var fileExtension = String()
  24. var fileId = String()
  25. override func viewDidLoad() {
  26. super.viewDidLoad()
  27. // Do any additional setup after loading the view.
  28. viewModel.delegate = self
  29. setupUI()
  30. // Add touch gesture to download view
  31. let downloadGesture = UITapGestureRecognizer(target: self, action: #selector(self.downloadPDF(sender:)))
  32. self.downloadView.addGestureRecognizer(downloadGesture)
  33. // Add touch gesture to upload view
  34. let uploadGesture = UITapGestureRecognizer(target: self, action: #selector(self.upload(sender:)))
  35. self.uploadView.addGestureRecognizer(uploadGesture)
  36. }
  37. func setupUI() {
  38. downloadView.layer.cornerRadius = 20
  39. downloadView.layer.borderWidth = 3
  40. downloadView.layer.borderColor = #colorLiteral(red: 0.00400000019, green: 0.200000003, blue: 0.3919999897, alpha: 1)
  41. uploadView.layer.cornerRadius = 20
  42. uploadView.layer.borderWidth = 3
  43. uploadView.layer.borderColor = #colorLiteral(red: 0.00400000019, green: 0.200000003, blue: 0.3919999897, alpha: 1)
  44. }
  45. @objc func downloadPDF(sender : UITapGestureRecognizer) {
  46. if Reachability.isConnectedToNetwork() {
  47. viewModel.downloadAssessment(fileId: fileId)
  48. } else {
  49. Alert.showInternetFailureAlert(on: self)
  50. }
  51. }
  52. // This will creates a PDF file
  53. func createPDF(with base64Info: String) {
  54. let base64Data = Data(base64Encoded: base64Info, options: .ignoreUnknownCharacters)
  55. let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
  56. let docName = "QuestionPaper-\(assessmentName)\(assessmentId).\(fileExtension)"
  57. let filePath = "\(documentsPath)/\(docName)"
  58. if FileManager.default.fileExists(atPath: filePath) {
  59. self.view.makeToast("File already exist!")
  60. } else {
  61. let url = URL(fileURLWithPath: filePath)
  62. do {
  63. try base64Data?.write(to: url, options: .atomic)
  64. self.view.makeToast("Download successful.")
  65. } catch let failedError {
  66. print("Failed to write the pdf data due to \(failedError.localizedDescription)")
  67. }
  68. }
  69. }
  70. @objc func upload(sender : UITapGestureRecognizer) {
  71. var documentPicker: UIDocumentPickerViewController!
  72. if #available(iOS 14, *) {
  73. // iOS 14 & later
  74. let supportedTypes: [UTType] = [UTType.pdf]
  75. documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes)
  76. } else {
  77. // iOS 13 or older code
  78. let supportedTypes: [String] = [kUTTypePDF as String]
  79. documentPicker = UIDocumentPickerViewController(documentTypes: supportedTypes, in: .import)
  80. }
  81. documentPicker.delegate = self
  82. documentPicker.allowsMultipleSelection = true
  83. documentPicker.modalPresentationStyle = .formSheet
  84. self.present(documentPicker, animated: true)
  85. }
  86. /*
  87. // MARK: - Navigation
  88. // In a storyboard-based application, you will often want to do a little preparation before navigation
  89. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  90. // Get the new view controller using segue.destination.
  91. // Pass the selected object to the new view controller.
  92. }
  93. */
  94. @IBAction func sideMenuAction(_ sender: UIBarButtonItem) {
  95. let menu = storyboard!.instantiateViewController(withIdentifier: "SideMenuNavigationController") as! SideMenuNavigationController
  96. present(menu, animated: true, completion: nil)
  97. }
  98. }
  99. extension OfflineAssessmentViewController: OfflineAssessmentProtocol {
  100. func startLoader() {
  101. ActivityIndicator.start()
  102. }
  103. func stopLoader() {
  104. ActivityIndicator.stop()
  105. }
  106. func showError(error: String) {
  107. self.view.makeToast(error)
  108. }
  109. func getDownloadedFile(base64:String) {
  110. self.createPDF(with: base64)
  111. }
  112. func moveToAssessment() {
  113. let vc = self.storyboard?.instantiateViewController(withIdentifier: "AssessmentBeneficiaryViewController") as! AssessmentBeneficiaryViewController
  114. self.navigationController?.pushViewController(vc, animated: true)
  115. }
  116. }
  117. extension OfflineAssessmentViewController: UIDocumentPickerDelegate {
  118. func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  119. for url in urls {
  120. // Start accessing a security-scoped resource.
  121. guard url.startAccessingSecurityScopedResource() else {
  122. // Handle the failure here.
  123. return
  124. }
  125. do {
  126. let data = try Data.init(contentsOf: url)
  127. print("url: \(url)")
  128. if Reachability.isConnectedToNetwork() {
  129. // You will have data of the selected file
  130. viewModel.uploadAssessment(assessmentId: assessmentId, userId: userData[0].id, fileType: "pdf", docData: data)
  131. } else {
  132. Alert.showInternetFailureAlert(on: self)
  133. }
  134. }
  135. catch {
  136. print(error.localizedDescription)
  137. }
  138. // Make sure you release the security-scoped resource when you finish.
  139. do { url.stopAccessingSecurityScopedResource() }
  140. }
  141. }
  142. func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
  143. controller.dismiss(animated: true, completion: nil)
  144. }
  145. }