Skip to content

Commit

Permalink
Cancel functionality while opening files (#348)
Browse files Browse the repository at this point in the history
* added cancel functionality while opening files
* fixed error message after cancel download tap
* fixed downloadCancelled not resetting to false
  • Loading branch information
ShresthPratapSingh authored Aug 28, 2020
1 parent dddd763 commit b93b2b1
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Lightbox
import CoreData
import AVFoundation
import GoogleCast
import Alamofire

internal protocol FilesView : BaseView {
func initFiles(_ files: [ServerFile])
Expand Down Expand Up @@ -46,6 +47,7 @@ class FilesPresenter: BasePresenter {
private var sessionManager: GCKSessionManager!

weak private var view: FilesView?
weak private var filesViewController: FilesViewController?
private var offlineFiles : [String: OfflineFile]?

var fetchedResultsController : NSFetchedResultsController<NSFetchRequestResult>? {
Expand All @@ -54,8 +56,9 @@ class FilesPresenter: BasePresenter {
}
}

init(_ view: FilesView) {
self.view = view
init(_ viewController: FilesViewController) {
filesViewController = viewController
self.view = viewController
}

func detachView() {
Expand Down Expand Up @@ -162,7 +165,7 @@ class FilesPresenter: BasePresenter {
let fileURL = FileManager.default.localPathInCache(for: selectedFile)
handleFileOpening(with: fileURL)
} else {
downloadFile(at: indexPath.item, section: indexPath.section, selectedFile, mimeType: type, from: sender) { fileURL in
filesViewController?.currentDownloadRequest = downloadFile(at: indexPath.item, section: indexPath.section, selectedFile, mimeType: type, from: sender) { fileURL in
handleFileOpening(with: fileURL)
}
}
Expand All @@ -178,7 +181,7 @@ class FilesPresenter: BasePresenter {
let path = FileManager.default.localPathInCache(for: file)
self.view?.shareFile(at: path, from: sender)
} else {
downloadFile(at: fileIndex, section: section, file, mimeType: file.mimeType, from: sender) { [weak self] filePath in
filesViewController?.currentDownloadRequest = downloadFile(at: fileIndex, section: section, file, mimeType: file.mimeType, from: sender) { [weak self] filePath in
self?.view?.shareFile(at: filePath, from: sender)
}
}
Expand Down Expand Up @@ -223,8 +226,7 @@ class FilesPresenter: BasePresenter {
_ serverFile: ServerFile,
mimeType: MimeType,
from sender : UIView?,
completion: @escaping (_ filePath: URL) -> Void) {

completion: @escaping (_ filePath: URL) -> Void) -> DownloadRequest? {
self.view?.updateDownloadProgress(for: fileIndex, section: section, downloadJustStarted: true, progress: 0.0)

// cleanup temp files in background
Expand All @@ -233,12 +235,15 @@ class FilesPresenter: BasePresenter {
folderName: "cache")
}

Network.shared.downloadFileToStorage(file: serverFile, progressCompletion: { progress in
let downloadRequest = Network.shared.downloadFileToStorage(file: serverFile, progressCompletion: { progress in
self.view?.updateDownloadProgress(for: fileIndex, section: section, downloadJustStarted: false, progress: progress)
}, completion: { (wasSuccessful) in

if !wasSuccessful {
self.view?.showError(message: StringLiterals.errorDownloadingFileMessage)
if !(self.filesViewController?.downloadCancelled ?? false){
self.view?.showError(message: StringLiterals.errorDownloadingFileMessage)
}
self.filesViewController?.downloadCancelled = false
return
}

Expand All @@ -248,6 +253,7 @@ class FilesPresenter: BasePresenter {
completion(filePath)
})
})
return downloadRequest
}

func loadOfflineFiles() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ extension FilesViewController: FilesView {

}

if !isAlertShowing {
if !isAlertShowing && downloadProgressAlertController != nil {
self.isAlertShowing = true
present(downloadProgressAlertController!, animated: true, completion: nil)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import UIKit
import Lightbox
import AVFoundation
import Alamofire
import GoogleCast
import Floaty

Expand All @@ -31,7 +32,7 @@ class FilesViewController: BaseUIViewController, GCKRemoteMediaClientListener {
print("setMediaInfo: \(String(describing: mediaInfo))")
}
}

var currentDownloadRequest:DownloadRequest?
public var sessionManager: GCKSessionManager!
public var mediaInformation: GCKMediaInformation?
public var mediaClient: GCKRemoteMediaClient!
Expand All @@ -55,6 +56,7 @@ class FilesViewController: BaseUIViewController, GCKRemoteMediaClientListener {
internal var filteredFiles = FilteredServerFiles()

internal var fileSort: FileSort!
var downloadCancelled = false

/*
KVO context used to differentiate KVO callbacks for this class versus other
Expand Down Expand Up @@ -455,7 +457,16 @@ class FilesViewController: BaseUIViewController, GCKRemoteMediaClientListener {

internal func setupDownloadProgressIndicator() {
downloadProgressAlertController = UIAlertController(title: "", message: "", preferredStyle: .alert)
downloadProgressAlertController?.view.setAnchorSize(width: nil, height: 190)
downloadProgressAlertController?.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: { _ in
self.downloadCancelled = true
self.currentDownloadRequest?.cancel(createResumeData: true)
self.downloadProgressAlertController?.dismiss(animated: true, completion: nil)
self.currentDownloadRequest = nil
self.downloadProgressAlertController = nil
self.progressView = nil
self.isAlertShowing = false
}))
downloadProgressAlertController?.view.setAnchorSize(width: nil, height: 220)

downloadTitleLabel = UILabel()
downloadTitleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
Expand Down Expand Up @@ -490,7 +501,7 @@ class FilesViewController: BaseUIViewController, GCKRemoteMediaClientListener {
stackView.alignment = .fill

downloadProgressAlertController?.view.addSubview(stackView)
stackView.setAnchors(top: downloadProgressAlertController?.view.topAnchor, leading: downloadProgressAlertController?.view.leadingAnchor, trailing: downloadProgressAlertController?.view.trailingAnchor, bottom: downloadProgressAlertController?.view.bottomAnchor, topConstant: 20, leadingConstant: 20, trailingConstant: 20, bottomConstant: 20)
stackView.setAnchors(top: downloadProgressAlertController?.view.topAnchor, leading: downloadProgressAlertController?.view.leadingAnchor, trailing: downloadProgressAlertController?.view.trailingAnchor, bottom: downloadProgressAlertController?.view.bottomAnchor, topConstant: 20, leadingConstant: 20, trailingConstant: 20, bottomConstant: 50)
}

// MARK: - Navigation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

import CoreData
import Alamofire

extension RecentFilesViewController{

Expand Down Expand Up @@ -119,7 +120,7 @@ extension RecentFilesViewController{
return offlineFiles?[file.fileName]
}

func downloadFile(recentFile: Recent, completion: @escaping(_ filePath: URL) -> Void){
func downloadFile(recentFile: Recent, completion: @escaping(_ filePath: URL) -> Void) -> DownloadRequest?{
updateDownloadProgress(recentFile: recentFile, downloadJustStarted: true, progress: 0.0)

// cleanup temp files in background
Expand All @@ -128,11 +129,14 @@ extension RecentFilesViewController{
folderName: "cache")
}

Network.shared.downloadRecentFileToStorage(recentFile: recentFile, progressCompletion: { (progress) in
let request = Network.shared.downloadRecentFileToStorage(recentFile: recentFile, progressCompletion: { (progress) in
self.updateDownloadProgress(recentFile: recentFile, downloadJustStarted: false, progress: progress)
}) { (wasSuccessfull) in
if !wasSuccessfull{
self.showError(message: StringLiterals.errorDownloadingFileMessage)
if !self.downloadCancelled{
self.showError(message: StringLiterals.errorDownloadingFileMessage)
}
self.downloadCancelled = false
return
}

Expand All @@ -142,6 +146,7 @@ extension RecentFilesViewController{
completion(filePath)
})
}
return request
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ extension RecentFilesViewController{
}
}

if !isAlertShowing{
if !isAlertShowing && downloadProgressAlertController != nil{
isAlertShowing = true
present(downloadProgressAlertController!, animated: true, completion: nil)
}
Expand All @@ -38,7 +38,15 @@ extension RecentFilesViewController{

func setupDownloadProgressIndicator(){
downloadProgressAlertController = UIAlertController(title: "", message: "", preferredStyle: .alert)
downloadProgressAlertController?.view.setAnchorSize(width: nil, height: 190)
downloadProgressAlertController?.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: { _ in
self.downloadCancelled = true
self.currentFileDownloadRequest?.cancel(createResumeData: true)
self.downloadProgressAlertController?.dismiss(animated: true, completion: nil)
self.downloadProgressAlertController = nil
self.progressView = nil
self.isAlertShowing = false
}))
downloadProgressAlertController?.view.setAnchorSize(width: nil, height: 220)


downloadTitleLabel = UILabel()
Expand Down Expand Up @@ -68,7 +76,7 @@ extension RecentFilesViewController{
stackView.alignment = .fill

downloadProgressAlertController?.view.addSubview(stackView)
stackView.setAnchors(top: downloadProgressAlertController?.view.topAnchor, leading: downloadProgressAlertController?.view.leadingAnchor, trailing: downloadProgressAlertController?.view.trailingAnchor, bottom: downloadProgressAlertController?.view.bottomAnchor, topConstant: 20, leadingConstant: 20, trailingConstant: 20, bottomConstant: 20)
stackView.setAnchors(top: downloadProgressAlertController?.view.topAnchor, leading: downloadProgressAlertController?.view.leadingAnchor, trailing: downloadProgressAlertController?.view.trailingAnchor, bottom: downloadProgressAlertController?.view.bottomAnchor, topConstant: 20, leadingConstant: 20, trailingConstant: 20, bottomConstant: 50)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import SDWebImage
import AVFoundation
import GoogleCast
import CoreData
import Alamofire

class RecentFilesViewController: BaseUIViewController {

Expand All @@ -32,12 +33,15 @@ class RecentFilesViewController: BaseUIViewController {
internal var isAlertShowing = false

var offlineFiles : [String: OfflineFile]?
var currentFileDownloadRequest:DownloadRequest?
var fetchedResultsController : NSFetchedResultsController<NSFetchRequestResult>? {
didSet {
executeSearch()
}
}

var downloadCancelled = false

private func executeSearch() {
if let fc = fetchedResultsController {
do {
Expand Down Expand Up @@ -241,7 +245,7 @@ class RecentFilesViewController: BaseUIViewController {
let fileURL = FileManager.default.localPathInCache(for: recentFile)
handleFileOpening(with: fileURL)
} else {
downloadFile(recentFile: recentFile) { (url) in
currentFileDownloadRequest = downloadFile(recentFile: recentFile) { (url) in
handleFileOpening(with: url)
}
}
Expand All @@ -255,7 +259,7 @@ class RecentFilesViewController: BaseUIViewController {
let path = FileManager.default.localPathInCache(for: recentFile)
shareFile(at: path, from: sender)
}else{
downloadFile(recentFile: recentFile) { (url) in
currentFileDownloadRequest = downloadFile(recentFile: recentFile) { (url) in
self.shareFile(at: url, from: sender)
}
}
Expand Down
14 changes: 8 additions & 6 deletions AmahiAnywhere/AmahiAnywhere/Utils/Network.swift
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public class Network {

func downloadRecentFileToStorage(recentFile: Recent,
progressCompletion: @escaping (_ percent: Float) -> Void,
completion: @escaping (_ isSuccessful: Bool ) -> Void) {
completion: @escaping (_ isSuccessful: Bool ) -> Void) -> DownloadRequest?{
// Create destination URL
let destination: DownloadRequest.DownloadFileDestination = { _, _ in

Expand All @@ -159,9 +159,9 @@ public class Network {
return (destinationFileUrl!, [.removePreviousFile, .createIntermediateDirectories])
}

guard let fileURL = URL(string: recentFile.fileURL) else { return }
guard let fileURL = URL(string: recentFile.fileURL) else { return nil}

Alamofire.download(fileURL, to: destination)
let request = Alamofire.download(fileURL, to: destination)
.downloadProgress { progress in
progressCompletion(Float(progress.fractionCompleted))
}
Expand All @@ -173,11 +173,12 @@ public class Network {
completion(false)
}
}
return request
}

public func downloadFileToStorage(file: ServerFile,
progressCompletion: @escaping (_ percent: Float) -> Void,
completion: @escaping (_ isSuccessful: Bool ) -> Void) {
completion: @escaping (_ isSuccessful: Bool ) -> Void) -> DownloadRequest? {

// Create destination URL
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
Expand All @@ -192,10 +193,10 @@ public class Network {

guard let fileUrl = ServerApi.shared!.getFileUri(file) else {
AmahiLogger.log("Invalid file URL, attempt to download file failed")
return
return nil
}

Alamofire.download(fileUrl, to: destination)
let downloadRequest = Alamofire.download(fileUrl, to: destination)
.downloadProgress { progress in
progressCompletion(Float(progress.fractionCompleted))
}
Expand All @@ -212,5 +213,6 @@ public class Network {
completion(false)
}
}
return downloadRequest
}
}

0 comments on commit b93b2b1

Please sign in to comment.