2

TL;DR Is there any common pattern of using NSURLSession in whole application by simply creating a new client class just the way you subclass AFHTTPSessionManager?


I like to use AFNetworking for many reasons and if I see no contraindications I use it with a pleasure but sometimes I've got a relatively simple task to achieve and AFNetworking seems to be an overkill or I simply need to avoid third party dependencies.

With that in my mind I realise that guys from Apple provided us with a cool thing called NSURLSession and it sounds like a perfect soultion for many cases but when I star reading about using it in projects, well I want to get back to AFNetworking let me explain why...

When you plan to create a custom class for your networking task using AFNetworking you simply create a subclass of AFHTTPSessionManager (of course if you're dealing with HTTP) and simply return singleton and so on... (If you don't know the rest of the story, check this great tutorial)
Simple, right?
But what if I want to subclass NSURLSession in the same way? Well, I'm still searching the Internet for a solution but so far no luck here... Every tutorial, every article, every post state that you instantiate NSURLSession in your view controller and if needed you use it, period. But what happend in case I want to use this client throughout my whole application?

cojoj
  • 6,405
  • 4
  • 30
  • 52
  • Why do you need a subclass? What are you trying to achieve by subclassing? – jtbandes Feb 10 '15 at 06:58
  • @jtbandes I want to create a class which I'll be able to use everywhere in my app to create a calls to external API. I don't want to put boilerplate `NSURL..` code everywhere insted I'd like to call more meningful methods like `fetchAllUsers:` or so. – cojoj Feb 10 '15 at 07:13

1 Answers1

2

For the use case you describe, it would be much simpler to make a singleton that has an NSURLSession as a property than to subclass it. See Prefer composition over inheritance?

Every tutorial, every article, every post state that you instantiate NSURLSession in your view controller and if needed you use it, period.

A view controller should typically not have any NSURL… classes in it, because a view controller should be told what to display, it shouldn't be asking. It's way outside the realm of what a view controller should do.

Community
  • 1
  • 1
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • So what you're trying to tell me is to drop the idea of inheritance here and create a regular class which will be a singleton. That makes sens! – cojoj Feb 10 '15 at 07:21