pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Wed, 01 Jun 2016 08:20:29 +0200
changeset 275 d26b9eb3165e
parent 273 12d01eaa52fe
child 324 efaf19804ced
child 334 841503ae98bf
permissions -rw-r--r--
Refresh mails
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@275
    14
    var isSynching: Bool = false
dirk@58
    15
}
dirk@58
    16
dirk@31
    17
class EmailListViewController: UITableViewController {
dirk@273
    18
    let comp = "EmailListViewController"
dirk@273
    19
    let segueShowEmail = "segueShowEmail"
dirk@30
    20
dirk@31
    21
    var appConfig: AppConfig?
dirk@212
    22
    var fetchController: NSFetchedResultsController?
dirk@275
    23
    var state = UIState()
dirk@275
    24
dirk@275
    25
    override func viewDidLoad() {
dirk@275
    26
        let refreshController = UIRefreshControl.init()
dirk@275
    27
        refreshController.addTarget(self, action: #selector(self.refresh(_:)),
dirk@275
    28
                                    forControlEvents: UIControlEvents.ValueChanged)
dirk@275
    29
        self.refreshControl = refreshController
dirk@275
    30
    }
dirk@31
    31
dirk@31
    32
    override func viewWillAppear(animated: Bool) {
dirk@31
    33
        if appConfig == nil {
dirk@31
    34
            if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
dirk@31
    35
                appConfig = appDelegate.appConfig
dirk@31
    36
            }
dirk@273
    37
        }
dirk@209
    38
        prepareFetchRequest()
dirk@209
    39
ana@152
    40
        let account:IAccount? = appConfig!.model.fetchLastAccount()
ana@152
    41
        if (account == nil)  {
ana@152
    42
            self.performSegueWithIdentifier("userSettings", sender: self)
ana@207
    43
        } else {
dirk@275
    44
            fetchMailsRefreshControl()
ana@152
    45
        }
ana@207
    46
        super.viewWillAppear(animated)
ana@207
    47
    }
ana@152
    48
dirk@275
    49
    func refresh(refreshControl: UIRefreshControl) {
dirk@275
    50
        fetchMailsRefreshControl(refreshControl)
dirk@275
    51
    }
dirk@275
    52
dirk@275
    53
    func fetchMailsRefreshControl(refreshControl: UIRefreshControl? = nil) {
dirk@115
    54
        if let account = appConfig?.model.fetchLastAccount() {
dirk@55
    55
            let connectInfo = account.connectInfo
dirk@55
    56
dirk@275
    57
            state.isSynching = true
dirk@67
    58
            appConfig!.grandOperator.prefetchEmails(
dirk@55
    59
                connectInfo, folder: ImapSync.defaultImapInboxName, completionBlock: {
dirk@67
    60
                    [unowned self] error in
dirk@58
    61
                    GCD.onMain({
dirk@67
    62
                        Log.info(self.comp, "Sync completed, error: \(error)")
dirk@275
    63
                        self.state.isSynching = false
dirk@275
    64
                        refreshControl?.endRefreshing()
dirk@149
    65
                        self.updateUI()
dirk@58
    66
                    })
ana@207
    67
                })
dirk@149
    68
            updateUI()
dirk@55
    69
        }
dirk@31
    70
    }
dirk@31
    71
dirk@196
    72
    @IBAction func newAccountCreatedSegue(segue: UIStoryboardSegue) {
dirk@275
    73
        fetchMailsRefreshControl()
dirk@196
    74
    }
dirk@196
    75
ana@143
    76
    func prepareFetchRequest() {
dirk@31
    77
        let predicates: [NSPredicate] = [NSPredicate.init(value: true)]
dirk@31
    78
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@31
    79
        fetchRequest.predicate = NSCompoundPredicate.init(
dirk@31
    80
            andPredicateWithSubpredicates: predicates)
dirk@119
    81
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "originationDate", ascending: false)]
dirk@31
    82
        fetchController = NSFetchedResultsController.init(
dirk@31
    83
            fetchRequest: fetchRequest,
dirk@31
    84
            managedObjectContext: appConfig!.coreDataUtil.managedObjectContext,
dirk@31
    85
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
    86
        fetchController?.delegate = self
dirk@31
    87
        do {
dirk@31
    88
            try fetchController?.performFetch()
dirk@31
    89
        } catch let err as NSError {
dirk@31
    90
            Log.error(comp, error: err)
dirk@31
    91
        }
dirk@31
    92
    }
dirk@31
    93
dirk@58
    94
    // MARK: - UI State
dirk@58
    95
dirk@58
    96
    func updateUI() {
dirk@275
    97
        if state.isSynching {
dirk@58
    98
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
    99
        } else {
dirk@58
   100
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
   101
        }
dirk@58
   102
    }
dirk@58
   103
dirk@31
   104
    // MARK: - UITableViewDataSource
dirk@31
   105
dirk@31
   106
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@209
   107
        if let count = fetchController?.sections?.count {
dirk@209
   108
            return count
dirk@209
   109
        } else {
dirk@209
   110
            return 0
dirk@209
   111
        }
dirk@31
   112
    }
dirk@31
   113
dirk@31
   114
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   115
        if fetchController?.sections?.count > 0 {
dirk@31
   116
            if let sections = fetchController?.sections {
dirk@31
   117
                let sectionInfo = sections[section]
dirk@31
   118
                return sectionInfo.numberOfObjects
dirk@31
   119
            }
dirk@31
   120
        }
dirk@31
   121
        return 0
dirk@31
   122
    }
dirk@31
   123
dirk@31
   124
    override func tableView(tableView: UITableView,
dirk@31
   125
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@209
   126
        let cell = tableView.dequeueReusableCellWithIdentifier(
dirk@209
   127
            "EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@31
   128
        configureCell(cell, indexPath: indexPath)
dirk@31
   129
        return cell
dirk@31
   130
    }
dirk@31
   131
dirk@31
   132
    func putString(string: String?, toLabel: UILabel) {
dirk@31
   133
        if string?.characters.count > 0 {
dirk@31
   134
            toLabel.hidden = false
dirk@31
   135
            toLabel.text = string!
dirk@31
   136
        } else {
dirk@31
   137
            toLabel.hidden = true
dirk@31
   138
        }
dirk@31
   139
    }
dirk@31
   140
dirk@31
   141
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   142
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@31
   143
            putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@31
   144
            putString(email.subject, toLabel: cell.subjectLabel)
dirk@31
   145
            putString(nil, toLabel: cell.summaryLabel)
dirk@32
   146
dirk@119
   147
            if let originationDate = email.originationDate {
dirk@32
   148
                let formatter = NSDateFormatter.init()
dirk@32
   149
                formatter.dateStyle = .ShortStyle
dirk@32
   150
                formatter.timeStyle = .ShortStyle
dirk@119
   151
                putString(formatter.stringFromDate(originationDate), toLabel: cell.dateLabel)
dirk@32
   152
            } else {
dirk@32
   153
                putString(nil, toLabel: cell.dateLabel)
dirk@32
   154
            }
dirk@31
   155
        }
dirk@30
   156
    }
dirk@30
   157
ana@246
   158
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
ana@246
   159
        if segue.identifier == "composeSegue" {
ana@246
   160
            let destination = segue.destinationViewController as! ComposeViewController
ana@246
   161
            destination.appConfig = appConfig
dirk@273
   162
        } else if segue.identifier == segueShowEmail {
dirk@273
   163
            guard
dirk@273
   164
                let vc = segue.destinationViewController as? EmailViewController,
dirk@273
   165
                let cell = sender as? UITableViewCell,
dirk@273
   166
                let indexPath = self.tableView.indexPathForCell(cell),
dirk@273
   167
                let email = fetchController?.objectAtIndexPath(indexPath) as? Message else {
dirk@273
   168
                    return
dirk@273
   169
            }
dirk@273
   170
            vc.appConfig = appConfig
dirk@273
   171
            vc.message = email
ana@246
   172
        }
ana@246
   173
    }
ana@246
   174
dirk@30
   175
}
dirk@30
   176
dirk@31
   177
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   178
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   179
        tableView.beginUpdates()
dirk@30
   180
    }
dirk@30
   181
dirk@31
   182
    func controller(controller: NSFetchedResultsController,
dirk@31
   183
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   184
                                     atIndex sectionIndex: Int,
dirk@31
   185
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   186
        switch (type) {
dirk@31
   187
        case .Insert:
dirk@31
   188
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   189
                                     withRowAnimation: .Fade)
dirk@31
   190
        case .Delete:
dirk@31
   191
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   192
                                     withRowAnimation: .Fade)
dirk@31
   193
        default:
dirk@31
   194
            Log.info(comp, "unhandled changeSectionType: \(type)")
dirk@31
   195
        }
dirk@30
   196
    }
dirk@30
   197
dirk@31
   198
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   199
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   200
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   201
                                              newIndexPath: NSIndexPath?) {
dirk@40
   202
        switch type {
dirk@40
   203
        case .Insert:
dirk@40
   204
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   205
        case .Delete:
dirk@40
   206
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   207
        case .Update:
dirk@40
   208
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   209
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   210
            } else {
dirk@40
   211
                Log.warn(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   212
            }
dirk@40
   213
        case .Move:
dirk@40
   214
            if newIndexPath != indexPath {
dirk@40
   215
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   216
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   217
            }
dirk@31
   218
        }
dirk@31
   219
    }
dirk@31
   220
dirk@31
   221
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   222
        tableView.endUpdates()
dirk@31
   223
    }
dirk@30
   224
}