Jonathan Wareham
Jonathan Wareham

Reputation: 3399

iOS - Perform synchronous HTTP request with AFNetworking

I'm currently migrating my app from using ASIHTTPRequest to AFNetworking. I know synchronous requests are to be avoided if possible, but in my app I have just 1 place where I use one. In the app delegate applicationDidEnterBackground() method I need to run a HTTP request to query data to set the application badge number when the app goes to background. When run asynchronously this rarely works because the method just drops out and the application is suspended before the HTTP request completes. With ASIHTTPRequest I used the [request startSynchronous] method and this meant the HTTP request completed 100% every time and the badge was updated correctly. I see with AFNetworking there is no obvious synchronous option, so can anybody suggest a way it can be used synchronously, or an alternative solution?

Upvotes: 2

Views: 3150

Answers (1)

Jonathan Wareham
Jonathan Wareham

Reputation: 3399

Have found the way to do this - using one of the AFHTTPRequestOperation derivatives there is the method - setShouldExecuteAsBackgroundTaskWithExpirationHandler: which gives the operation extra time to complete before the OS suspends the app. So my code is :

[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:nil];
[operation start];

This was just what I needed and has solved my problem.

Jonathan

UPDATE: As Bob has pointed out using this method does not actually perform the operation synchronously, but was the ideal solution in my case in the absence of a synchronous method.

Upvotes: 6

Related Questions