You have a few options to handle our work in the background. You can use it, for example, DispatchQueue simple task or OperationQueue.
OperaionQueue handles Operations instances to work in the background. If the system allows then each operation is executed in a separate thread. Operation is a single task which need be done in the background, for example, download files, clean database or delete old files.
A single instance of OperationQueue is thread-safe and can be used from many threads.
Let’s say you have a function to saveFile(name: String). This method saves some files from the API based on the name.
You want to save many files.
First, create an instance of OperationQueue and few URL’s mocks.
let files = [“photosUrl”, “musicUrl”, “moviesUrl”]
let queue = OperationQueue()
Then, create the Operation to save for each URL name.
for file in files {
queue.addOperation {
self.saveFile(name: file)
// saveFile is some function, not included here
}
}
And it’s done. Each function execution will be in the background and other thread if the system allows for it.
But if you do it in an empty project on the simulator you will see that all executions are at the same time. If you need to force OperationQueue to do it one by one you need to set maxConcurrentOperationCount before adding operation.
//After creating OperationQueue instance
queue.maxConcurrentOperationCount = 1
//Before adding Operation to OperationQueue
There is also an option to stop code execution and wait for operations execution.
//Adding Operation to OperationQueue
queue.waitUntilAllOperationsAreFinished()
Use this after adding Operations. But don’t do this on the main thread.