@ -23,19 +23,21 @@ class Downloader: NSObject, ObservableObject {
private ( set ) lazy var downloadState : CurrentValueSubject < DownloadState , Never > = CurrentValueSubject ( . notStarted )
private var stateSubscriber : Cancellable ?
private var urlSession : URLSession ? = nil
init ( from url : URL , to destination : URL ) {
self . destination = destination
super . init ( )
// . b a c k g r o u n d a l l o w s d o w n l o a d s t o p r o c e e d i n t h e b a c k g r o u n d
let config = URLSessionConfiguration . background ( withIdentifier : " net.pcuenca.diffusion.download " )
let urlSession = URLSession ( configuration : config , delegate : self , delegateQueue : OperationQueue ( ) )
urlSession = URLSession ( configuration : config , delegate : self , delegateQueue : OperationQueue ( ) )
downloadState . value = . downloading ( 0 )
urlSession .getAllTasks { tasks in
urlSession ? .getAllTasks { tasks in
// I f t h e r e ' s a n e x i s t i n g p e n d i n g b a c k g r o u n d t a s k , l e t i t p r o c e e d , o t h e r w i s e s t a r t a n e w o n e .
// TODO: c h e c k U R L w h e n w e s u p p o r t d o w n l o a d i n g m o r e m o d e l s .
if tasks . first = = nil {
urlSession . downloadTask ( with : url ) . resume ( )
self . urlSession ? . downloadTask ( with : url ) . resume ( )
}
}
}
@ -59,6 +61,10 @@ class Downloader: NSObject, ObservableObject {
default : throw ( " Should never happen, lol " )
}
}
func cancel ( ) {
urlSession ? . invalidateAndCancel ( )
}
}
extension Downloader : URLSessionDelegate , URLSessionDownloadDelegate {