0

I have a list of files i need to upload to my server.

I want to upload each file only if the file before it uploaded successfully.

I'm looking for an elegant way to implement this.

For example using coroutines like feature.

So is there a feature like coroutines in swift?

Is there any other elegant way to implement this?

Thanks

ilan
  • 4,402
  • 6
  • 40
  • 76
  • Use a DispatchQueue. See these links for reference: https://forums.developer.apple.com/thread/53270 https://developer.apple.com/documentation/dispatch/dispatchqueue – Scriptable Jan 11 '18 at 15:19
  • 1
    You can manage such things with OperationQueue. Reference :- https://developer.apple.com/documentation/foundation/nsoperationqueue – Aman.Samghani Jan 11 '18 at 15:19
  • Write a(n asynchronous) function that takes the index of the file to upload and a completion. Withing this function, use Foundation's network library to upload. Provide the function, with index incremented, as the completion. – BallpointBen Jan 11 '18 at 15:21

3 Answers3

3

You could use an OperationQueue. Create one like this:

lazy var queue: OperationQueue = {
    let queue = OperationQueue()
    queue.maxConcurrentOperationCount = 1

    return queue
}()

and then add an operation to it like this:

self.queue.addOperation {
    // The code you want run in the background
}

Having set the maxConcurrentOperationCount to 1 it operates as a serial queue not running the next task until the current one has finished.

That's the most basic functionality but there are all kinds of more advanced things you can do so check out the documentation OperationQueue

Upholder Of Truth
  • 4,643
  • 2
  • 13
  • 23
0

Why not create a List of files and on the completion handler of one upload just check if the list is not empty and kick off the next one? Rather than a complicated coroutines setup I think it can be simpler by just maintaining an upload list/queue.

davidethell
  • 11,708
  • 6
  • 43
  • 63
0

You can create a serial queue for that, using Grand Central Dispatch. Compared to OperationQueue suggested in on of the answers given here it has the advantage of saving quite an amount of overhead. Please see this post for details on that.

This creates the serial queue:

let serialQueue = DispatchQueue(label: "someQueueIdentifier", qos: .background)

Choose the quality of service parameter according to your needs.

Then, you could have a loop, for example, from which you place your background jobs into this queue:

while <condition> {
    serialQueue.async {
        // do background job
    }
}

A serial queue will run one job at a time and the whole queue will be executed asynchronously in the background.

Tom E
  • 1,530
  • 9
  • 17