Where to put URL requests in your iOS app code?

It’s hard to imagine an iOS application that doesn’t perform URL requests. If you develop iOS apps you should have done it a lot of times. But are you sure that you put your request code in the appropriate place?

I had a chance to maintain many different apps and very often I saw the same “pattern” – put all network interaction code directly in the view controller!

Imagine SomeViewController.m:

AFNetworking is a popular networking library so I put it in the example. What’s wrong with that code? Plenty of things:

  • When someone opens the controller’s code he sees a lot of redundant stuff such as the URL string generation, the request initialization, the creation of the AFHTTPRequestOperation etc. All these things make code less readable (make the code worse yeah).
  • There’s no single place to handle such things as session expiration, server side errors etc.
  • If you need to replace AFHTTPRequestOperation to any other request loading stuff you will have to modify all URL requests in your project.
  • Looks ugly.

Well, what is the better way? It’s really obvious and I wonder why so many developers don’t follow this simple rule – hide complexity. Just put all URL loading in a different class. Make a separate function for every different API call.

In this approach loadDataFromWebservice would look like this:

Looks better, doesn’t it?

I also prefer to use promises for asynchronous operations. There is an awesome PromiseKit library for Objective-C and Swift. It allows to make chained operations without nested blocks. Just return promise from APIService:

Here you can see that loadDataWithAction request uses data obtained in loadCurrentAction. Much more readable without nested blocks.

This approach is applicable to almost everything. Have a complex code? Put it to separate file/class/function etc. View configuration in UIViewController? Better do it in the custom view class. Say no to giant view controllers.

Good luck :)