Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.90 KB | None | 0 0
  1. let cellId = "cellId"
  2. var fetchedStatsArray: [NSManagedObject] = []
  3.  
  4. fileprivate lazy var fetchedResultsController: NSFetchedResultsController<AlarmItem> = {
  5. //create fetch request
  6. let fetchRequest: NSFetchRequest<AlarmItem> = AlarmItem.fetchRequest()
  7.  
  8. //configure fetch request
  9. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "alarmAttributes", ascending: true)]
  10. let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  11.  
  12. let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
  13.  
  14. let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  15.  
  16. fetchedResultsController.delegate = self
  17.  
  18. return fetchedResultsController
  19. }()
  20.  
  21. func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
  22. tableView.beginUpdates()
  23. }
  24.  
  25. func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
  26. tableView.endUpdates()
  27. }
  28.  
  29. func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
  30.  
  31. switch(type) {
  32. case .insert:
  33. if let indexPath = newIndexPath {
  34. tableView.insertRows(at: [indexPath], with: .fade)
  35. }
  36. break;
  37. case .delete:
  38. if let indexPath = indexPath {
  39. tableView.deleteRows(at: [indexPath], with: .fade)
  40. }
  41. break;
  42. case .update:
  43. //this is mostlikely where the problem lies
  44. //self.tableView.reloadData()
  45. if let indexPath = indexPath, let cell = tableView.cellForRow(at: indexPath) {
  46. configureCell(cell, at: indexPath)
  47. }
  48. break;
  49. case .move:
  50. if let indexPath = indexPath {
  51. tableView.deleteRows(at: [indexPath], with: .fade)
  52. }
  53. if let newIndexPath = newIndexPath {
  54. tableView.insertRows(at: [newIndexPath], with: .fade)
  55. }
  56. break;
  57. @unknown default:
  58. print("Something odd is happening")
  59. }
  60. }
  61.  
  62.  
  63. override func viewDidLoad() {
  64. super.viewDidLoad()
  65.  
  66.  
  67. override func viewWillAppear(_ animated: Bool) {
  68. super.viewWillAppear(animated)
  69. do {
  70. try fetchedResultsController.performFetch()
  71. } catch let err as NSError {
  72. print("Failed to fetch items", err)
  73. }
  74. }
  75.  
  76. @objc func addAlarmItem(_ sender: AnyObject) {
  77. let alertController = UIAlertController(title: "Add New Item", message: "Please fill in the blanks", preferredStyle: .alert)
  78. let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
  79.  
  80. //combined string of attributes
  81. let myStrings: [String] = alertController.textFields!.compactMap { $0.text }
  82. let myText = myStrings.joined(separator: ",")
  83.  
  84. self.save(myText)
  85. self.tableView.reloadData()
  86. }
  87.  
  88. let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
  89.  
  90. alertController.addTextField { (textField) in
  91. textField.placeholder = "Enter Name of Engineer"
  92. }
  93. alertController.addTextField { (textField) in
  94. textField.placeholder = "Enter Date of Alarm in DD/MM/YYYY"
  95. }
  96. alertController.addTextField { (textField) in
  97. textField.placeholder = "Enter Time of Alarm in 24h (eg: 2300)"
  98. }
  99. alertController.addTextField { (textField) in
  100. textField.placeholder = "Please indicate True/False (type True or False)"
  101. }
  102. alertController.addTextField { (textField) in
  103. textField.placeholder = "Insert comments (if any), or NIL"
  104. }
  105.  
  106.  
  107. if let popoverController = alertController.popoverPresentationController {
  108. popoverController.sourceView = self.view;
  109. popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0.0, height: 0.0)
  110. popoverController.permittedArrowDirections = []
  111. popoverController.barButtonItem = self.navigationItem.leftBarButtonItem
  112. }
  113. self.present(alertController, animated: true, completion: nil)
  114. }
  115.  
  116. func save(_ itemName: String) {
  117. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  118. let managedContext = appDelegate.persistentContainer.viewContext
  119. let entity = NSEntityDescription.entity(forEntityName: "AlarmItem", in: managedContext)!
  120. let item = NSManagedObject(entity: entity, insertInto: managedContext)
  121. item.setValue(itemName, forKey: "alarmAttributes")
  122.  
  123. do {
  124. try managedContext.save()
  125. tableView.reloadData()
  126.  
  127. } catch let err as NSError {
  128. print("Failed to save an item", err)
  129. }
  130. }
  131.  
  132. @objc func exportCSV(_ sender: AnyObject) {
  133. exportDatabase()
  134. }
  135.  
  136. func exportDatabase() {
  137. let exportString = createExportString()
  138. saveAndExport(exportString: exportString)
  139. }
  140.  
  141. func saveAndExport(exportString: String) {
  142. let exportFilePath = NSTemporaryDirectory() + "itemlist.csv"
  143. let exportFileUrl = NSURL(fileURLWithPath: exportFilePath)
  144. FileManager.default.createFile(atPath: exportFilePath, contents: NSData() as Data, attributes: nil)
  145. var fileHandle: FileHandle? = nil
  146.  
  147. do {
  148. fileHandle = try FileHandle(forUpdating: exportFileUrl as URL)
  149. } catch {
  150. print("filehandle has error")
  151. }
  152.  
  153. if fileHandle != nil {
  154. fileHandle!.seekToEndOfFile()
  155. let csvData = exportString.data(using: String.Encoding.utf8, allowLossyConversion: false)
  156. fileHandle!.write(csvData!)
  157. fileHandle!.closeFile()
  158.  
  159. let firstActivityItem = NSURL(fileURLWithPath: exportFilePath)
  160. let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [firstActivityItem], applicationActivities: nil)
  161.  
  162. activityViewController.excludedActivityTypes = [
  163. UIActivity.ActivityType.assignToContact,
  164. UIActivity.ActivityType.saveToCameraRoll,
  165. UIActivity.ActivityType.postToFlickr,
  166. UIActivity.ActivityType.postToVimeo,
  167. UIActivity.ActivityType.postToTencentWeibo
  168. ]
  169. activityViewController.popoverPresentationController?.sourceView = self.view
  170. activityViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection()
  171. activityViewController.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
  172. self.present(activityViewController, animated: true, completion: nil)
  173. }
  174. }
  175.  
  176. func createExportString() -> String {
  177. var alarmAttributes: String?
  178. var export: String = NSLocalizedString("Engineer Name,Date of Alarm,Time of Alarm,True or False,Engineer Comments n", comment: "")
  179.  
  180. for (index, AlarmItem) in fetchedStatsArray.enumerated() {
  181. if index <= fetchedStatsArray.count - 1 {
  182. alarmAttributes = AlarmItem.value(forKey: "alarmAttributes") as! String?
  183. let alarmAttributeStrings = alarmAttributes
  184. export += "(alarmAttributeStrings ?? "0") n"
  185. }
  186. }
  187. print("the app will now print: (export) ")
  188. return export
  189. }
  190.  
  191. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
  192. let sectionInfo = fetchedResultsController.sections![section]
  193. return sectionInfo.numberOfObjects
  194. }
  195.  
  196. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  197. let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
  198. let alarmItem = fetchedResultsController.object(at: indexPath) as NSManagedObject
  199. cell.textLabel?.text = alarmItem.value(forKeyPath: "alarmAttributes") as? String
  200. return cell
  201. }
  202.  
  203. func tableView(_ tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
  204. return true
  205. }
  206.  
  207. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  208. tableView.deselectRow(at: indexPath, animated: true)
  209. }
  210.  
  211. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
  212. guard editingStyle == .delete else { return }
  213.  
  214. //fetch
  215. let toBeDeleted = fetchedResultsController.object(at: indexPath)
  216.  
  217. //delete
  218. fetchedResultsController.managedObjectContext.delete(toBeDeleted)
  219.  
  220. do {
  221. try fetchedResultsController.managedObjectContext.save()
  222. } catch let err as NSError {
  223. print("failed to save item", err)
  224. }
  225.  
  226. }
  227.  
  228. func tableView(_tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  229. let cell = tableView.dequeueReusableCell(withIdentifier: "AlarmItem", for: indexPath)
  230. configureCell(cell, at: indexPath)
  231.  
  232. return cell
  233. }
  234.  
  235. func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) {
  236. let alarmItem = fetchedResultsController.object(at: indexPath)
  237.  
  238. //configure cell
  239. cell.textLabel?.text = alarmItem.value(forKeyPath: "alarmAttributes") as? String
  240. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement