Calling sync POST with parameters in Xcode

528 views Asked by At

I found many samples of code to sending a POST request using NSURL & dispatch_sync but none that sends parameters like AFHTTPRequestOperationManager does. Would someone supply a reference or a code snippet?

I need to send text, numbers and images.

1

There are 1 answers

0
Rob On

If doing network requests, you should always perform them asynchronously. If you want to block the UI while awaiting a response from the server, don't make the request synchronous, but rather keep it asynchronous, but present the UI that indicates that the user must wait for the response (e.g. a UIActivityIndicatorView or the like; you can also consider using MBProgressHUD). But do not perform synchronous requests. It's a horrible UX and the watchdog process may kill your app.

If you absolutely must do your request synchronously, rather than creating your own post requests, you could stay with AFNetworking, but use semaphores to make the asynchronous request behave in synchronous manner. Create a dispatch semaphore (dispatch_semaphore_create), signal the semaphore inside the AFNetworking completion blocks (dispatch_semaphore_signal), wait for the signal after the asynchronous method (dispatch_semaphore_wait).

The trick with AFNetworking would be that you'd simply have to make sure the completionQueue of the AFHTTPRequestOperationManager or AFHTTPSessionManager is not the main queue (i.e. set it to be a global queue or a queue that you create yourself). If you don't change the completionQueue, you'll deadlock if use a semaphore on the main queue.

But, again, I can't say this strongly enough: The whole notion of doing synchronous requests from the main thread is ill-conceived. It's a horrible idea. Don't do it.