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