9
func authenticate(completion:(success: Bool) -> Void) {
let qos = Int(QOS_CLASS_USER_INITIATED.value)
dispatch_async(dispatch_get_global_queue(qos, 0)){ () -> Void in
    Alamofire.request(.POST, CONSTANTS.Domain+"/accounts", parameters: ["" : ""]).responseJSON { (req, res, json, error)  in
         dispatch_async(dispatch_get_main_queue()){
               completion(success: true)
         }
    }
}
}

Or, can I leave out the dispatch and just keep my code simple?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • As an aside, when you do need a global queue, you don't have to get the `value` for the qos and then create `Int` from that. There's a rendition of `dispatch_get_global_queue` that takes `qos_class_t` parameter directly. In this case it's moot, as `NSURLSession`-based solutions don't need to be dispatched to background thread at all, but just for future reference. – Rob Apr 10 '15 at 04:54

1 Answers1

6

Alamofire is designed to be asynchronous. On another note, if the method has as callback, most likely it is asynchronous. So, yes you can leave out the dispatch_async calls.

mattt
  • 19,544
  • 7
  • 73
  • 84
Schemetrical
  • 5,506
  • 2
  • 26
  • 43
  • 3
    Agreed, though the presumption that if it has a closure that it runs asynchronously is less and less true. The historical counter examples were enumeration blocks and predicates, but with Swift functional programming, we use synchronous closures quite a bit. Also, the fact that with Alamofire the inner block doesn't need to get dispatched back to the main queue is an implementation detail that can only be confirmed by reading the docs/code. More often than not, when you have asynchronous closures, they do _not_ run on the main thread, though for Alamofire they do. – Rob Apr 10 '15 at 05:04
  • @Rob yeah thats true, I forgot about block enumeration and such. – Schemetrical Apr 10 '15 at 06:08
  • Older versions of Alamofire seemed to kick my ass frequently when I forgot to add a main_queue block, doesn't seem to happen anymore. Is it still true that I *should* wrap all my callbacks and I just got lucky a few times? – Lucas van Dongen Nov 10 '15 at 01:07
  • @DepartamentoB you can try yourself by putting a breakpoint in the callback and checking which thread the breakpoint stopped. – Schemetrical Nov 11 '15 at 03:10
  • 1
    I tried a few times and I noticed it's always Thread 1. But there's a world of difference between *always* and *most of the time* ;) – Lucas van Dongen Nov 11 '15 at 12:19