pEpForiOS/ViewControllers/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Tue, 19 Apr 2016 10:30:34 +0200
changeset 40 c27435589f2e
parent 32 b0f40f51538b
permissions -rw-r--r--
Better adherence to NSFetchedResultsController
dirk@30
     1
//
dirk@30
     2
//  EmailListViewController.swift
dirk@30
     3
//  pEpForiOS
dirk@30
     4
//
dirk@30
     5
//  Created by Dirk Zimmermann on 16/04/16.
dirk@30
     6
//  Copyright © 2016 p≡p Security S.A. All rights reserved.
dirk@30
     7
//
dirk@30
     8
dirk@30
     9
import Foundation
dirk@30
    10
import UIKit
dirk@31
    11
import CoreData
dirk@30
    12
dirk@31
    13
class EmailListViewController: UITableViewController {
dirk@31
    14
    let comp = "EmailListViewController"
dirk@30
    15
dirk@31
    16
    var appConfig: AppConfig?
dirk@31
    17
    var fetchController: NSFetchedResultsController?
dirk@31
    18
dirk@31
    19
    override func viewWillAppear(animated: Bool) {
dirk@31
    20
        if appConfig == nil {
dirk@31
    21
            if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
dirk@31
    22
                appConfig = appDelegate.appConfig
dirk@31
    23
            }
dirk@31
    24
        }
dirk@31
    25
        prepareFetchRequest()
dirk@31
    26
        super.viewWillAppear(animated)
dirk@31
    27
    }
dirk@31
    28
dirk@31
    29
    func prepareFetchRequest() {
dirk@31
    30
        let predicates: [NSPredicate] = [NSPredicate.init(value: true)]
dirk@31
    31
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@31
    32
        fetchRequest.predicate = NSCompoundPredicate.init(
dirk@31
    33
            andPredicateWithSubpredicates: predicates)
dirk@31
    34
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "sentDate", ascending: false)]
dirk@31
    35
        fetchController = NSFetchedResultsController.init(
dirk@31
    36
            fetchRequest: fetchRequest,
dirk@31
    37
            managedObjectContext: appConfig!.coreDataUtil.managedObjectContext,
dirk@31
    38
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
    39
        fetchController?.delegate = self
dirk@31
    40
        do {
dirk@31
    41
            try fetchController?.performFetch()
dirk@31
    42
        } catch let err as NSError {
dirk@31
    43
            Log.error(comp, error: err)
dirk@31
    44
        }
dirk@31
    45
    }
dirk@31
    46
dirk@31
    47
    // MARK: - UITableViewDataSource
dirk@31
    48
dirk@31
    49
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@31
    50
        return (fetchController?.sections?.count)!
dirk@31
    51
    }
dirk@31
    52
dirk@31
    53
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
    54
        if fetchController?.sections?.count > 0 {
dirk@31
    55
            if let sections = fetchController?.sections {
dirk@31
    56
                let sectionInfo = sections[section]
dirk@31
    57
                return sectionInfo.numberOfObjects
dirk@31
    58
            }
dirk@31
    59
        }
dirk@31
    60
        return 0
dirk@31
    61
    }
dirk@31
    62
dirk@31
    63
    override func tableView(tableView: UITableView,
dirk@31
    64
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@31
    65
        let cell = tableView.dequeueReusableCellWithIdentifier("EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@31
    66
        configureCell(cell, indexPath: indexPath)
dirk@31
    67
        return cell
dirk@31
    68
    }
dirk@31
    69
dirk@31
    70
    func putString(string: String?, toLabel: UILabel) {
dirk@31
    71
        if string?.characters.count > 0 {
dirk@31
    72
            toLabel.hidden = false
dirk@31
    73
            toLabel.text = string!
dirk@31
    74
        } else {
dirk@31
    75
            toLabel.hidden = true
dirk@31
    76
        }
dirk@31
    77
    }
dirk@31
    78
dirk@31
    79
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
    80
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@31
    81
            putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@31
    82
            putString(email.subject, toLabel: cell.subjectLabel)
dirk@31
    83
            putString(nil, toLabel: cell.summaryLabel)
dirk@32
    84
dirk@32
    85
            if let sentDate = email.sentDate {
dirk@32
    86
                let formatter = NSDateFormatter.init()
dirk@32
    87
                formatter.dateStyle = .ShortStyle
dirk@32
    88
                formatter.timeStyle = .ShortStyle
dirk@32
    89
                putString(formatter.stringFromDate(sentDate), toLabel: cell.dateLabel)
dirk@32
    90
            } else {
dirk@32
    91
                putString(nil, toLabel: cell.dateLabel)
dirk@32
    92
            }
dirk@31
    93
        }
dirk@30
    94
    }
dirk@30
    95
dirk@30
    96
}
dirk@30
    97
dirk@31
    98
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
    99
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   100
        tableView.beginUpdates()
dirk@30
   101
    }
dirk@30
   102
dirk@31
   103
    func controller(controller: NSFetchedResultsController,
dirk@31
   104
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   105
                                     atIndex sectionIndex: Int,
dirk@31
   106
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   107
        switch (type) {
dirk@31
   108
        case .Insert:
dirk@31
   109
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   110
                                     withRowAnimation: .Fade)
dirk@31
   111
        case .Delete:
dirk@31
   112
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   113
                                     withRowAnimation: .Fade)
dirk@31
   114
        default:
dirk@31
   115
            Log.info(comp, "unhandled changeSectionType: \(type)")
dirk@31
   116
        }
dirk@30
   117
    }
dirk@30
   118
dirk@31
   119
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   120
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   121
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   122
                                              newIndexPath: NSIndexPath?) {
dirk@40
   123
        switch type {
dirk@40
   124
        case .Insert:
dirk@40
   125
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   126
        case .Delete:
dirk@40
   127
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   128
        case .Update:
dirk@40
   129
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   130
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   131
            } else {
dirk@40
   132
                Log.warn(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   133
            }
dirk@40
   134
        case .Move:
dirk@40
   135
            if newIndexPath != indexPath {
dirk@40
   136
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   137
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   138
            }
dirk@31
   139
        }
dirk@31
   140
    }
dirk@31
   141
dirk@31
   142
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   143
        tableView.endUpdates()
dirk@31
   144
    }
dirk@30
   145
}