I have a function performSync which runs through an array and for each item in this array, I am calling a function which in itself contains an async alamofire request. I need to be able to tell when this outer function has completed running all functions within the for loop, so I need to add a completion handler. I am unsure how to implement this.
Also, in my for loop, I have used .userinitiated in order to try and not block the ui thread, however the thread is being blocked. I also tried using the commented out concurrent queue method, but that also blocked the UI.
Code below:
public class Sync {
public class func onPerformSync(finished: () -> Void){
let syncList = ['Process1', 'Process2', 'Process3']
//let concurrentQueue = DispatchQueue(label: "concurrentQueue", attributes: .concurrent)
for item in syncList {
//concurrentqueue.async
DispatchQueue.global(qos: .background).async {
let className = "appname."+item
let ClassObj = NSClassFromString(className)! as! Helper_Base.Type
ClassObj.doSync()
}
//multiple classes extend Helper_Base and override the doSync func
//I realise there may be a swiftier way to call these doSync methods rather than instantiating from a string and overriding the base class
//doSync and I'd welcome advice on it!
}
//calling finished here is fine if I use a synchronous dispatchQueue but where do i place this line since I need my queue to be asynchronous?
finished()
}
}
open class Process1 : Helper_Base {
override open class func doSync(){
let time = Int64(NSDate().timeIntervalSince1970 * 1000)
repeatBlock(time: time)
}
open class func repeatBlock(time : Int64){
let parameters : [String : String] = [
"x" : time
]
var continueSync : Bool = false
DispatchQueue.global(qos: .background).async {
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default)
.response { response in
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
guard let utf8TextDecoded = utf8Text.fromBase64() else {
return
}
let error = response.error
if error == nil
{
do {
let json = try JSONSerializer.toDictionary(utf8TextDecoded)
let more = json["more"] as! Bool
continueSync = more
}
}
}
if continueSync {
let time = Int64(NSDate().timeIntervalSince1970 * 1000)
DispatchQueue.global(qos: .background).async {
repeatBlock(time: time)
}
}
else{
finishSync()
}
}
}
}
open class func finishSync(){
//other stuff
}
}
Sync.onPerformSync(){
print("we're done syncing")
}