1

I'm new to background operations in iOS, so I'm wondering what is the best way to solve such problem:

I have data, coming from one webservice#1 that needed to be parsed and sent to webservice#2 in background.

I need a background thread, which will be listening for changes in array that stores data from webserivce#1 and when it's not empty, the thread will start uploadOperation, which will process the array and send processed data to webservice#2

Literally, how I see it: I have DataManager class, presented by a Singleton sharedInstance.

let sharedInstance = DataManager()

It has

public var data: [String]? {
    didSet {
        processData()
    }   
}

private var uploadToWebSerivice2Queue: NSOperationQueue?

private override init() {
    uploadToWebSerivice2Queue = NSOperationQueue()
    uploadToWebSerivice2Queue.maxConcurentOperations = 1
    getCachedAndNotSentDataFromDatabase()
}

private func getCachedAndNotSentDataFromDatabase() {
    data = ("string 1", "string 2", "string 3", "string 4")
}

private func processData() {

    while let lastElement = data!.removeLast {
        let processedData = process(lastElement)
        let uploadOperation = UploadOperation(processedData) // Data upload opeation
        uploadToWebSerivice2Queue!.addOperation(uploadOperation)
    }

}

Some data may come from Database where they are cached if they couldn't be send to webservice#2 during the last try. And some data may come from webservice#1 in runtime.

So in other class, let's call it Webservice1DataHandler, I'd do:

DataManager.sharedInstance.data.append("New string to process and upload to webservice#1")

To sum up, var data will be set after first init() and uploadQueue will start to process that data. Then new string will be appended to var data, that means that processData() method will be invoked and concurecny problems with data array access may occur.

I'm not sure if my algorithm is OK.

autobot
  • 139
  • 9
  • 2
    Why bother with the data array? Why not simply call a method that puts another upload operation on the queue. By using an array you have possible concurrency issues with updates to the array. So you would just say `DataManager.sharedInstance.processData(somedata)` – Paulw11 Sep 29 '15 at 12:29
  • That's exactly what I was aware of. Invoking processData for each part of freshly arrived data didn't come in to my mind. Thanks. – autobot Sep 29 '15 at 12:37
  • @Paulw11, however, it might become a problem if I need to process freshly arrived data first. In this case I can use data array as a stack (LIFO). – autobot Sep 29 '15 at 12:48
  • 1
    Yes, but you will need to ensure that access to the array is made thread safe - http://stackoverflow.com/questions/28191079/create-thread-safe-array-in-swift – Paulw11 Sep 29 '15 at 19:44
  • @Paulw11 I like this approach, thanks again. – autobot Sep 30 '15 at 11:32

0 Answers0