• Home
  • DSA
  • Concept
  • Interview
  • Tips&Tricks
  • Tutorial Videos
  • Home
  • DSA
  • Concept
  • Interview
  • Tips&Tricks
  • Tutorial Videos
  • #News
  • #APPS
  • #Events
    • #WWDC
    • #I/O
    • #Ignite
  • #Let’s Talk
  • #Advertise

MyCodeTips mycodetips-newlogocopy1

  • Home
  • DSA
  • Concept
  • Interview
  • Tips&Tricks
  • Tutorial Videos
IOS

How to download the task using URLSessionDownloadDelegate

How to download the task using URLSessionDownloadDelegate

URLSessionDownloadDelegate : By passing days the mobile APP is going more UX and UI friendly . Listening uninterrupted music or videos or browsing infifine scroll in a APP that means APP has to download something from the internet, be it images, data or pdf files or whatever. While your app downloads the required resources, your user has to wait. Now, this isn’t an issue if the resources are small or can be fetched really fast. What if the process isn’t fast enough or the resource is very large (say size in MB in double or even triple digits!)? Your users will have to stare at a blank screen with a probably unresponsive app (depending on how you handled resource loading) which is a deal-breaker and may lead users away from your app. You must do something to assure the users that the required resource is indeed loading and the app isn’t stuck at some deadlock. Show them some progress. Animation, text, percentage labels — whatever goes with your app.

A protocol defining methods that URL session instances call on their delegates to handle task-level events specific to download tasks.

in addition to the methods in this protocol, be sure to implement the methods in the URLSessionTaskDelegate and URLSessionDelegate protocols to handle events common to all task types and session-level events, respectively.

func urlSession(URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo: URL)

func urlSession(URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset: Int64, expectedTotalBytes: Int64)

func urlSession(URLSession, downloadTask: URLSessionDownloadTask, didWriteData: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)

func downloadTask(with: URL) -> URLSessionDownloadTask
Creates a download task that retrieves the contents of the specified URL and saves the results to a file.

func downloadTask(with: URL, completionHandler: (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask

Creates a download task that retrieves the contents of the specified URL, saves the results to a file, and calls a handler upon completion.

class YourDownloadDelegate: YourAPPDelegate, URLSessionDownloadDelegate {

var yourdownloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }

var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?

var resumeData: Data?

override var data: Data? { return resumeData }

var destination: DownloadRequest.DownloadFileDestination?
var tempURL: URL?
var destinationURL: URL?

var fileURL: URL? { return destination != nil ? destinationURL : tempURL }
override init(task: URLSessionTask?) {
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()

progress = Progress(totalUnitCount: 0)
resumeData = nil
}

/

/ called when Finishing the downloading process

var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
// Downloading task written or saving

var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?

var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
tempURL = location

guard
let destination = destination,
let response = downloadTask.response as? HTTPURLResponse
else { return }

let result = destination(location, response)
let destinationURL = result.destinationURL
let options = result.options

self.destinationURL = destinationURL

do {
if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) {
try FileManager.default.removeItem(at: destinationURL)
}

if options.contains(.createIntermediateDirectories) {
let directory = destinationURL.deletingLastPathComponent()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
try FileManager.default.moveItem(at: location, to: destinationURL)
} catch {
self.error = error
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }

// Downloading Task Written

if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten

if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
Liked it? Take a second to support Ranjan on Patreon!
become a patron button
  • Click to share on Reddit (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • More
  • Click to share on Pocket (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
Written by Ranjan - 4877 Views
AUTHOR
Ranjan

Namaste, My name is Ranjan, I am a graduate from NIT Rourkela. This website is basically about of what i learnt from my years of experience as a software engineer on software development specifically on mobile application development, design patterns/architectures, its changing scenarios, security, troubleshooting, tools, tips&tricks and many more.

Next Post
Previous Post

Support us

mycodetips mycodetips
Follow us @ LinkedIn 2850+

Subscribe for updates

Join 8,213 other subscribers

Latest Posts

  • YT-Featured-solidprinciples
    SOLID Principles of Software Design
  • IOS 16 Features
    Latest features in IOS 16
  • r-language
    How can R language be used for data analysis?
  • wordpress-coding-blog
    Guide To WordPress Coding Standards
  • YT-Featured-Algorithm
    What is Algorithm?
  • Frameworks of IOS
    Frameworks of IOS – Part ( I )
  • NSFileManager or NSPathUtilities
    NSFileManager or NSPathUtilities in Objective-C
  • Passing data between view controllers in Objective-C
    Passing data between view controllers in Objective-C
  • structures-classes-enum
    Structures and Classes in swift !
  • control-system-swift
    Control Flow in Swift
whiteboard

Whiteboard(PRO)

whiteboard

Whiteboard(lite)

alphabets

Kids Alphabet

techlynk

Techlynk

techbyte

Do2Day

techbyte

Techbyte

  • #about
  • #myapps
  • #contact
  • #privacy
  • #Advertise
  • #Guestpost
  • #myQuestions

Android Android Studio API APP Programming Apps blogging CSS DATABASE dsa Features HTML HTML5 installation Interview Questions IOS iPhone javascript Mac objective-c OS Programming quicktips SDK SEO SQL swift Tips & Tricks Tools UI Web Wordpress Xcode

  • SOLID Principles of Software Design
  • Latest features in IOS 16
  • How can R language be used for data analysis?
  • Guide To WordPress Coding Standards
  • What is Algorithm?

©mycodetips.com