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