danywarner danywarner - 5 months ago 13
Swift Question

How do I create a Singleton Serial Queue with GCD?

This is what I am using (inside a class called Utils.swift)

static let serialQueue = dispatch_queue_create("com.wi-mobile.wmForms", DISPATCH_QUEUE_SERIAL)

However, it seems like I create a new queue everytime I call something like


I would need it to be within another class as I can't instantiate a new queue every time I get into the ViewController I need it to run.

I need to dispatch some network calls, but I need the UI to return immediately after calling the first one, however I need all of them to run serially.


I am using callbacks, and maybe there's where my serialization fails, here's an example:

func sendFormToMiddleware() {

successSending = false
errorSending = false

let seconds: String = String(NSDate().timeIntervalSince1970)

let tbvotos: TbvotosDB = TbvotosDB(survey_id: idForm, transaction_id: "\(WMConfiguration.getTranid())", lu_date: seconds , id_movil: WMConfiguration.getUser(), status: "1")

dispatch_async(UtilsUI.serialQueue) {
self.conectionHandler.doPostWmFormsService(self.attemptToSendForm, service: ConnectionHandler.Service.TBVOTOS, parameters: tbvotos.asArray()!)

func attemptToSendForm(isOk: Bool, mData: [AnyObject], isLastEntity: Bool) -> Void {
if isOk {
successSending = true
Queries.unifyTransactionIDForCurrentFormQuestions(idForm, tranId: WMConfiguration.getTranid())
let responses = Queries.getResponses(idForm)

dispatch_async(UtilsUI.serialQueue) {
self.conectionHandler.insertRespuestas(self.callbackEnvioRespuestas, responses: responses)

self.view.userInteractionEnabled = true
self.navigationController?.navigationBar.userInteractionEnabled = true
} else {
self.view.userInteractionEnabled = true
self.navigationController?.navigationBar.userInteractionEnabled = true
errorSending = true
UtilsUI.showAlert(NSLocalizedString("Error al contactar con el Servidor", comment: "Fallo conexión middleware"), self)

Here doPostWmFormsService's first parameter (attemptToSendForm) is the callback function. I can't figure what other approach should I use in case I am right.


The question went out of scope in the comments, being it originally how to create a singleton queue in Swift, I must give credit to Phillip Mills as printing it twice print(UtilsUI.serialQueue) returns the same memory address, thus it is the same object and it's a singleton.