ios - Sharing NSURLsession delegate implementation among view controllers -


in ios app, many viewcontrollers need send/receive data server based on user input , actions. going use nsurlsession networking activities. don't want make every viewcontroller conform nsurlsession delegate protocol , repeat methods.

i see 2 solutions

  • create class conforms nsurlsession delegate protocol. other classes create instance of class , use methods send/receive data server. reuse of class handling networking done using singleton design pattern overloading init method instance of created.

    • disadvantage of approach seems having singletons make tough create unit tests gets functionality of each class isolated form others. i.e.suppose error happens because viewcontroler1 asked "shared class" send particular message followed viewcontroller 2 asked send other message. not possible catch using unit tests.
  • subclass of uiviewcontroller implements methods , subclass viewcontrollers of of this.

    • one issue here if have different kinds of views in app, need create subclass each type of viewcontroller nsurl session delegate methods. , have assign delegate object method method. when @ it, think approach has same unit-testing problem approach 1.

i appreciate comments on 1. approaches others have used in similar situation 2. pros/cons of above approaches (including 2 have listed above). realize may bit subjective, imho getting advice on design patterns important (or more important than) answers wrong code or api use solve problem x

the way i've done in past is:

1) created class contained nsurlsession object @interface customsession : nsurlsessiondelegate @property (nonatomic, strong) nsurlsession *mysession;

2) in customsession init method initialize mysession, set delegate self.

3) implemented desired nsurlsession delegate methods in customsession.

4) use block methods (optional, prefer them)

5) decide whether want use customsession singleton or instantiate every time need it. can both define init methods accordingly.

+ (customsession *)session {     //singleton }  + (instancetype) newclient{     //normal init method} 

6) unit testing, have weak pointer in customsession parent vc (as pointed out work if you're not using singleton).

quick suggestion: use afnetworking, simplify life. example use afhttpsessionmanager , corresponding block methods provided: [self get:detailsurl parameters:parameters success:^(nsurlsessiondatatask *task, id responseobject)


Comments