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.