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