Bug fixes

This commit is contained in:
Chris Li 2017-01-30 11:42:37 -05:00
parent de8de9d5df
commit df1c858b48
5 changed files with 57 additions and 31 deletions

View File

@ -225,7 +225,7 @@ class LibraryBooksController: CoreDataCollectionBaseController, UICollectionView
if isCloudTab { if isCloudTab {
let displayedLanguages = Language.fetch(displayed: true, context: managedObjectContext) let displayedLanguages = Language.fetch(displayed: true, context: managedObjectContext)
return NSCompoundPredicate(andPredicateWithSubpredicates: [ return NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "stateRaw == 0 OR stateRaw == 1"), NSPredicate(format: "stateRaw == 0"),
displayedLanguages.count > 0 ? NSPredicate(format: "language IN %@", displayedLanguages) : NSPredicate(format: "language.name != nil") displayedLanguages.count > 0 ? NSPredicate(format: "language IN %@", displayedLanguages) : NSPredicate(format: "language.name != nil")
]) ])
} else { } else {
@ -239,6 +239,7 @@ class LibraryBooksController: CoreDataCollectionBaseController, UICollectionView
try? fetchedResultController.performFetch() try? fetchedResultController.performFetch()
collectionView.reloadData() collectionView.reloadData()
} }
} }
extension Localized { extension Localized {

View File

@ -13,14 +13,17 @@ class CoreDataCollectionBaseController: UIViewController, NSFetchedResultsContro
@IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionView: UICollectionView!
private(set) var shouldReloadCollectionView = false private(set) var shouldReloadCollectionView = false {didSet{ print("shouldReload: \(shouldReloadCollectionView)")}}
private var closures = [() -> Void]() private var closures = [() -> Void]()
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any, at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type { switch type {
case .insert: case .insert:
guard collectionView.numberOfSections > 0, guard collectionView.numberOfSections > 0,
let newIndexPath = newIndexPath, let newIndexPath = newIndexPath,
newIndexPath.section + 1 <= collectionView.numberOfSections,
collectionView.numberOfItems(inSection: newIndexPath.section) > 0 else { collectionView.numberOfItems(inSection: newIndexPath.section) > 0 else {
shouldReloadCollectionView = true shouldReloadCollectionView = true
break break
@ -58,6 +61,7 @@ class CoreDataCollectionBaseController: UIViewController, NSFetchedResultsContro
OperationQueue.main.addOperation({ OperationQueue.main.addOperation({
if self.shouldReloadCollectionView { if self.shouldReloadCollectionView {
self.collectionView.reloadData() self.collectionView.reloadData()
self.closures.removeAll()
} else { } else {
self.collectionView.performBatchUpdates({ self.collectionView.performBatchUpdates({
self.closures.forEach({ $0() }) self.closures.forEach({ $0() })

View File

@ -22,7 +22,7 @@
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews> <subviews>
<collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="UY0-46-c3y"> <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="UY0-46-c3y">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="FMe-0w-Xez"> <collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="FMe-0w-Xez">

View File

@ -30,19 +30,23 @@ class Network: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionD
// MARK: - actions // MARK: - actions
func start(book: Book) { func startDownload(bookID: String) {
guard let url = book.url else {return} self.managedObjectContext.perform {
let task = (book.fileSize > 100000000 ? wifiSession: cellularSession).downloadTask(with: url) guard let book = Book.fetch(bookID, context: self.managedObjectContext) else {return}
task.taskDescription = book.id book.state = .local
task.resume() }
// guard let url = book.url else {return}
let downloadTask = DownloadTask.fetch(bookID: book.id, context: managedObjectContext) // let task = (book.fileSize > 100000000 ? wifiSession: cellularSession).downloadTask(with: url)
downloadTask?.state = .queued // task.taskDescription = book.id
// task.resume()
if self.managedObjectContext.hasChanges { try? self.managedObjectContext.save() } //
// let downloadTask = DownloadTask.fetch(bookID: book.id, context: managedObjectContext)
progresses[book.id] = 0 // downloadTask?.state = .queued
if progresses.count == 1 { startTimer() } //
// if self.managedObjectContext.hasChanges { try? self.managedObjectContext.save() }
//
// progresses[book.id] = 0
// if progresses.count == 1 { startTimer() }
} }
func pause(bookID: String) { func pause(bookID: String) {
@ -105,18 +109,23 @@ class Network: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionD
// MARK: - URLSessionTaskDelegate // MARK: - URLSessionTaskDelegate
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let bookID = task.taskDescription else {return}
if let data = (error as? NSError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data {
Preference.resumeData[bookID] = data
self.managedObjectContext.perform({
guard let book = Book.fetch(bookID, context: self.managedObjectContext) else {return}
book.downloadTask?.state = .paused
})
}
} }
// MARK: - URLSessionDownloadDelegate // MARK: - URLSessionDownloadDelegate
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
managedObjectContext.perform { managedObjectContext.perform {
guard let bookID = downloadTask.taskDescription else {return} guard let bookID = downloadTask.taskDescription,
let book = Book.fetch(bookID, context: self.managedObjectContext) else {return}
if book.state != .downloading {book.state = .downloading}
self.progresses[bookID] = totalBytesWritten self.progresses[bookID] = totalBytesWritten
} }
} }

View File

@ -88,17 +88,29 @@ extension AlertProcedure {
} }
static func bookMore(context: UIViewController, book: Book) -> AlertProcedure { static func bookMore(context: UIViewController, book: Book) -> AlertProcedure {
assert(Thread.isMainThread, "The more")
let alert = AlertProcedure(presentAlertFrom: context, withPreferredStyle: .actionSheet, waitForDismissal: true) let alert = AlertProcedure(presentAlertFrom: context, withPreferredStyle: .actionSheet, waitForDismissal: true)
alert.title = book.title alert.title = book.title
alert.add(actionWithTitle: Localized.Library.download, style: .default) { _ in if book.state == .cloud {
Network.shared.start(book: book) alert.add(actionWithTitle: Localized.Library.download, style: .default) { _ in
alert.finish() Network.shared.startDownload(bookID: book.id)
} alert.finish()
alert.add(actionWithTitle: Localized.Library.copyURL, style: .default) { _ in }
guard let url = book.url else {return} alert.add(actionWithTitle: Localized.Library.copyURL, style: .default) { _ in
UIPasteboard.general.string = url.absoluteString guard let url = book.url else {return}
alert.finish() UIPasteboard.general.string = url.absoluteString
alert.finish()
}
} else if book.state == .local {
alert.add(actionWithTitle: "set back to cloud", style: .default) { _ in
let context = AppDelegate.persistentContainer.viewContext
context.perform({
book.state = .cloud
})
alert.finish()
}
} }
alert.add(actionWithTitle: Localized.Common.cancel, style: .cancel) { _ in alert.finish() } alert.add(actionWithTitle: Localized.Common.cancel, style: .cancel) { _ in alert.finish() }
return alert return alert
} }