pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Fri, 06 May 2016 18:08:04 +0200
changeset 149 4f8e228e77cd
parent 145 be24683a1073
child 152 356806f5e175
permissions -rw-r--r--
comment in some uncommented lines
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@58
    13
struct UIState {
dirk@58
    14
    let runningOpsUser = NSMutableOrderedSet()
dirk@58
    15
    let runningOpsAuto = NSMutableOrderedSet()
dirk@58
    16
dirk@58
    17
    func isSynching() -> Bool {
dirk@58
    18
        return runningOpsUser.count > 0 || runningOpsAuto.count > 0
dirk@58
    19
    }
dirk@58
    20
dirk@58
    21
    func isSynchingAuto() -> Bool {
dirk@58
    22
        return runningOpsAuto.count > 0
dirk@58
    23
    }
dirk@58
    24
dirk@58
    25
    func isSynchingUser() -> Bool {
dirk@58
    26
        return runningOpsUser.count > 0
dirk@58
    27
    }
dirk@58
    28
}
dirk@58
    29
dirk@31
    30
class EmailListViewController: UITableViewController {
dirk@31
    31
    let comp = "EmailListViewController"
dirk@30
    32
dirk@31
    33
    var appConfig: AppConfig?
dirk@31
    34
    var fetchController: NSFetchedResultsController?
dirk@58
    35
    let state = UIState()
dirk@31
    36
dirk@31
    37
    override func viewWillAppear(animated: Bool) {
dirk@31
    38
        if appConfig == nil {
dirk@31
    39
            if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
dirk@31
    40
                appConfig = appDelegate.appConfig
dirk@31
    41
            }
dirk@31
    42
        }
ana@142
    43
        prepareFetchRequest()
dirk@55
    44
dirk@115
    45
        if let account = appConfig?.model.fetchLastAccount() {
dirk@55
    46
            let connectInfo = account.connectInfo
dirk@55
    47
dirk@67
    48
            appConfig!.grandOperator.prefetchEmails(
dirk@55
    49
                connectInfo, folder: ImapSync.defaultImapInboxName, completionBlock: {
dirk@67
    50
                    [unowned self] error in
dirk@58
    51
                    GCD.onMain({
dirk@67
    52
                        Log.info(self.comp, "Sync completed, error: \(error)")
dirk@149
    53
                        self.updateUI()
dirk@58
    54
                    })
dirk@55
    55
            })
dirk@149
    56
            updateUI()
dirk@55
    57
        }
dirk@149
    58
        super.viewWillAppear(animated)
dirk@31
    59
    }
dirk@31
    60
ana@143
    61
    func prepareFetchRequest() {
dirk@31
    62
        let predicates: [NSPredicate] = [NSPredicate.init(value: true)]
dirk@31
    63
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@31
    64
        fetchRequest.predicate = NSCompoundPredicate.init(
dirk@31
    65
            andPredicateWithSubpredicates: predicates)
dirk@119
    66
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "originationDate", ascending: false)]
dirk@31
    67
        fetchController = NSFetchedResultsController.init(
dirk@31
    68
            fetchRequest: fetchRequest,
dirk@31
    69
            managedObjectContext: appConfig!.coreDataUtil.managedObjectContext,
dirk@31
    70
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
    71
        fetchController?.delegate = self
dirk@31
    72
        do {
dirk@31
    73
            try fetchController?.performFetch()
dirk@31
    74
        } catch let err as NSError {
dirk@31
    75
            Log.error(comp, error: err)
dirk@31
    76
        }
dirk@31
    77
    }
dirk@31
    78
dirk@58
    79
    // MARK: - UI State
dirk@58
    80
dirk@58
    81
    func updateUI() {
dirk@58
    82
        if state.isSynching() {
dirk@58
    83
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
    84
        } else {
dirk@58
    85
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
    86
        }
dirk@58
    87
    }
dirk@58
    88
dirk@31
    89
    // MARK: - UITableViewDataSource
dirk@31
    90
dirk@31
    91
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@31
    92
        return (fetchController?.sections?.count)!
dirk@31
    93
    }
dirk@31
    94
dirk@31
    95
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
    96
        if fetchController?.sections?.count > 0 {
dirk@31
    97
            if let sections = fetchController?.sections {
dirk@31
    98
                let sectionInfo = sections[section]
dirk@31
    99
                return sectionInfo.numberOfObjects
dirk@31
   100
            }
dirk@31
   101
        }
dirk@31
   102
        return 0
dirk@31
   103
    }
dirk@31
   104
dirk@31
   105
    override func tableView(tableView: UITableView,
dirk@31
   106
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@31
   107
        let cell = tableView.dequeueReusableCellWithIdentifier("EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@31
   108
        configureCell(cell, indexPath: indexPath)
dirk@31
   109
        return cell
dirk@31
   110
    }
dirk@31
   111
dirk@31
   112
    func putString(string: String?, toLabel: UILabel) {
dirk@31
   113
        if string?.characters.count > 0 {
dirk@31
   114
            toLabel.hidden = false
dirk@31
   115
            toLabel.text = string!
dirk@31
   116
        } else {
dirk@31
   117
            toLabel.hidden = true
dirk@31
   118
        }
dirk@31
   119
    }
dirk@31
   120
dirk@31
   121
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   122
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@31
   123
            putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@31
   124
            putString(email.subject, toLabel: cell.subjectLabel)
dirk@31
   125
            putString(nil, toLabel: cell.summaryLabel)
dirk@32
   126
dirk@119
   127
            if let originationDate = email.originationDate {
dirk@32
   128
                let formatter = NSDateFormatter.init()
dirk@32
   129
                formatter.dateStyle = .ShortStyle
dirk@32
   130
                formatter.timeStyle = .ShortStyle
dirk@119
   131
                putString(formatter.stringFromDate(originationDate), toLabel: cell.dateLabel)
dirk@32
   132
            } else {
dirk@32
   133
                putString(nil, toLabel: cell.dateLabel)
dirk@32
   134
            }
dirk@31
   135
        }
dirk@30
   136
    }
dirk@30
   137
dirk@30
   138
}
dirk@30
   139
dirk@31
   140
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   141
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   142
        tableView.beginUpdates()
dirk@30
   143
    }
dirk@30
   144
dirk@31
   145
    func controller(controller: NSFetchedResultsController,
dirk@31
   146
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   147
                                     atIndex sectionIndex: Int,
dirk@31
   148
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   149
        switch (type) {
dirk@31
   150
        case .Insert:
dirk@31
   151
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   152
                                     withRowAnimation: .Fade)
dirk@31
   153
        case .Delete:
dirk@31
   154
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   155
                                     withRowAnimation: .Fade)
dirk@31
   156
        default:
dirk@31
   157
            Log.info(comp, "unhandled changeSectionType: \(type)")
dirk@31
   158
        }
dirk@30
   159
    }
dirk@30
   160
dirk@31
   161
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   162
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   163
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   164
                                              newIndexPath: NSIndexPath?) {
dirk@40
   165
        switch type {
dirk@40
   166
        case .Insert:
dirk@40
   167
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   168
        case .Delete:
dirk@40
   169
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   170
        case .Update:
dirk@40
   171
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   172
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   173
            } else {
dirk@40
   174
                Log.warn(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   175
            }
dirk@40
   176
        case .Move:
dirk@40
   177
            if newIndexPath != indexPath {
dirk@40
   178
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   179
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   180
            }
dirk@31
   181
        }
dirk@31
   182
    }
dirk@31
   183
dirk@31
   184
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   185
        tableView.endUpdates()
dirk@31
   186
    }
dirk@30
   187
}