MATTREAGAN
iOS & macOS engineer,
designer, game creator
Author: Matt Reagan
« Previous | Next »

Modal Windows with AFNetworking
If you're presenting a modal window on macOS and attempt to make network requests with AFNetworking, you might be surprised when those requests vanish into thin air. No timeouts, no errors - no result at all.

It can be easy to overlook the fact that methods like NSApplication -runModalForWindow: do not return until the modal session ends, and essentially freeze the main serial queue of Grand Central Dispatch (now simply 'Dispatch') in its tracks.

This is important when using libraries like AFNetworking which, by default, dispatch_async completion blocks to the main queue. The end result is that these blocks pile up but are unable to execute while your modal window is open. You won't receive any failures, errors, or responses - they're all stuck, waiting on your window to finish.

Solution

For AFNetworking, you can override or set -completionQueue to a background queue:

manager.completionQueue = dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAULT, 0)

Or DispatchQueue.global() in Swift

for your manager's requests. Your network completion blocks will then execute on a concurrent background queue without any problems.

Bear in mind the thread safety implications of this. If you need to update UI or perform mainthread-only work from these blocks, you can leverage -performSelectorOnMainThread: which doesn't rely on the main queue and works as expected even when a modal loop is running.

For libraries other than AFNetworking, the solution will depend on the API architecture. In general, however, anything that dispatches to the main queue will be impacted by your modal window and will require some accommodation if you expect it to work normally.

Sheets

The above is true for -runModalForWindow: and -runModalSession:. It is not true in the case of window-modal sheets, however, which do not block the main queue in the same way. Apple's modal window documentation is a recommended read and covers some of the nuances.

Acknowledgment

Kirby Turner wrote a very good blog post on this same topic, definitely worth checking out.