Decorating file downloader in iOS

Szymon Mrozek
May 28, 2018 · 4 min read
Decorating food, originally here

let queue: OperationQueue
let limit: Int // pre-defined
queue.maxConcurrentOperationCount = limit
let operation = BlockOperation(block: { [weak downloadItem] in
guard let item = downloadItem else { return }
let semaphore = DispatchSemaphore(value: 0)
item.completionBlock = { [weak semaphore] in
semaphore?.signal()
}
item.resume()
semaphore.wait()
})
queue.addOperation(operation)

func cedric(_ cedric: Cedric, didFinishWithMostRecentError error: Error?)
var delegates: MulticastDelegate<CedricDelegate>
delegates.invoke({ 
$0.cedric(self, didFinishWithMostRecentError: self.lastError)
})

public enum DownloadMode {
case newFile
case notDownloadIfExists
}
switch resource.mode { 
case .newFile:
items.append(item) // always schedule no matter if file exists
case .notDownloadIfExists:
if let existing = existingFile(for: resource.destination) {
delegates.invoke({ ... }) // notify about finish
return
} else {
// check is operation not already scheduled
guard !items.contains(resource) else { return }
items.append(item)
}
}
switch resource.mode {
case .newFile:
resultUrl = try fileManager.createUrl(forName: destination, unique: true)
case .notDownloadIfExists:
resultUrl = try fileManager.createUrl(forName: destination, unique: false)
}
func createUrl(forName name: String, unique: Bool) throws -> URL {
let downloads = try downloadsDirectory(create: true)
try createDownloadsDirectoryIfNeeded()

if unique {
return try uniquePath(forName: name)
} else {
return downloads.appendingPathComponent(name)
}
}

Final notes

  1. As you’ve probably already guessed I’ve written a library called Cedric, it’s written in pure Swift on top of URLSession, feel free to use it and suggest new features / fixes.
  2. This article is only an example, real implementation is a little bit more complicated but for making it more readable I’ve removed some unnecessary parts.
  3. Don’t forget to clap and follow if you like it 😎
  4. A huge thanks to my brother Mateusz for decorating my articles with correct grammar and general fixing of my English language mistakes.

AppUnite collection

We teach how to write apps