Basically all of the apps will involve the network, whether it is using afnetworking or their own HTTP request, the whole network framework is very important to build.
Landlord Package Network request class, including their own written HTTP request and afnetworking request, code is simple, mainly frame building. Simply put, there is a request class, a parsing class, and several data classes.
The following code takes the public weather query API as an example:
1. Network Request Class
I have the usual network request methods are encapsulated, you only need to write their own interface, passing apiname,params parameters such as can.
#pragmaMark iOS Request method//How iOS comes with get requests-(void) Getddbyurlpath: (NSString *) path Andparams: (NSString *)paramsandcallback: (CallBack) callback{if(params) {[path stringbyappendingstring:[nsstring stringWithFormat:@"?%@",params]]; } nsstring* Pathstr =[path stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; NSLog (@"url:%@", PATHSTR); Nsurl*url =[Nsurl Urlwithstring:pathstr]; Nsmutableurlrequest*request =[Nsmutableurlrequest Requestwithurl:url]; Nsurlsession*session =[Nsurlsession sharedsession]; Nsurlsessiondatatask*task = [Session datataskwithrequest:request completionhandler:^ (NSData *data, Nsurlresponse *response, NSError *error) {Dispatch_async (Dispatch_get_main_queue (),^{ IDJsondata = [nsjsonserialization jsonobjectwithdata:data options:0Error:nil]; NSLog (@"%@", Jsondata); if([Jsondata Iskindofclass:[nsarrayclass]]) {nsdictionary* dic = jsondata[0]; Callback (DIC); }Else{callback (jsondata); } }); }]; //Start Request[Task resume];}//How iOS comes with a POST request-(void) Postddbybyurlpath: (NSString *) path Andparams: (nsdictionary*)paramsandcallback: (CallBack) callback{Nsurl*url =[Nsurl Urlwithstring:path]; Nsmutableurlrequest*request =[Nsmutableurlrequest Requestwithurl:url]; [Request Sethttpmethod:@"POST"]; Nserror*error; if([Nsjsonserialization Isvalidjsonobject:params]) {NSData*jsondata = [Nsjsonserialization datawithjsonobject:paramsOptions:nsjsonwritingprettyprinted error:&ERROR]; [Request Sethttpbody:jsondata]; Nsurlsession*session =[Nsurlsession sharedsession]; Nsurlsessiondatatask*task = [Session datataskwithrequest:request completionhandler:^ (NSData *data, Nsurlresponse *response, NSError *error) {Dispatch_async (Dispatch_get_main_queue (),^{nsstring* str =[[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"..........%@", str); IDJsondata = [nsjsonserialization jsonobjectwithdata:data options:0Error:nil]; if([Jsondata Iskindofclass:[nsarrayclass]]) {nsdictionary* dic = jsondata[0]; Callback (DIC); }Else{callback (jsondata); } }); }]; //Start Request[Task resume]; }}#pragmaMark third-party request method//How to get requests from third parties-(void) Getbyapiname: (NSString *) Apiname Andparams: (ID)paramsandcallback: (CallBack) callback{[self.manager get:apiname parameters:paramssuccess:^ (Afhttprequestoperation *operation,IDresponseobject) {callback (Responseobject); } Failure:^ (Afhttprequestoperation *operation, Nserror *error) {Callback (nil); }]; }//third-party POST request mode-(void) Postbyapiname: (NSString *) Apiname Andparams: (ID)paramsandcallback: (CallBack) callback{[self.manager post:apiname parameters:paramssuccess:^ (Afhttprequestoperation *operation,IDresponseobject) {callback (Responseobject); } Failure:^ (Afhttprequestoperation *operation, Nserror *error) {Callback (nil); }]; }//third-party post upload image request method-(void) Postimagebyapiname: (NSString *) Apiname Andparams: (ID)paramsAndimagesarray: (nsarray*) Images Andback: (CallBack) callback{[self.manager post:apiname parameters:paramsconstructingbodywithblock:^ (IDformData) { for(inti =0; i<images.count; i++) {NSData* ImageData = UIImageJPEGRepresentation (Images[i],0.8); NSString* Name =Nil; if(Images.count = =1) {Name=@"ImageFile"; }Else{Name= [NSString stringWithFormat:@"file%d", i+1]; } [FormData appendpartwithfiledata:imagedata name:name filename:[nsstring stringWithFormat:@"image.jpg"] MimeType:@"Image/jpeg"]; }} Success:^ (Afhttprequestoperation *operation,IDresponseobject) {callback (Responseobject); } Failure:^ (Afhttprequestoperation *operation, Nserror *error) {Callback (nil); }];}-(void) Postimagebyapiname: (NSString *) apiname andimagename: (nsstring*) imageName Andparams: (ID)paramsAndimage: (uiimage*) Image andback: (CallBack) callback{NSData* ImageData = uiimagejpegrepresentation (image,0.8); [Self.manager post:apiname parameters:paramsconstructingbodywithblock:^ (IDformData) {[FormData appendpartwithfiledata:imagedata name:imagename filename:[nsstring stringWithFormat:@"image.jpg"] MimeType:@"Image/jpeg"]; } Success:^ (Afhttprequestoperation *operation,IDresponseobject) {callback (Responseobject); } Failure:^ (Afhttprequestoperation *operation, Nserror *error) {Callback (nil); }];}
Take the weather query as an example, write an interface yourself, select the request method:
-(void ) Getweathercallback: (CallBack) callback{ // Select the request method you want, we use a GET request from a non-third party, Select a different request method, which is the asynchronous request [self Getddbyurlpath: @ " http://m.weather.com.cn/data/101190101.html andparams:nil andcallback:^ (id obj) { // [Wtparseweather Parseweatherbyweatherdic:obj]; // return parsed data
2 parsing classes, this different data to different parsing classes, write yourself, this is the weather example:
+ (Weather *) Parseweatherbyweatherdic: (Nsdictionary *) dic{nsdictionary* Weatherinfodic = [Dic objectforkey:@"Weatherinfo"]; Weather* Weainfo =[[Weather alloc]init]; Weainfo.city= [Weatherinfodic Objectforkey:@" City"]; Weainfo.date= [Weatherinfodic Objectforkey:@"date_y"]; Weainfo.week= [Weatherinfodic Objectforkey:@"Week"]; Weainfo.wind= [Weatherinfodic Objectforkey:@"Wind1"]; Weainfo.weather= [Weatherinfodic Objectforkey:@"Weather1"]; Weainfo.tip= [Weatherinfodic Objectforkey:@"Index"]; returnWeainfo;}
3 request where the network is requested
- (void) getnetdata{[[Wtnetworkingmanager sharewtnetworkingmanager]getweathercallback:^(IDobj) {Weather* Weainfo =obj; Self.weatherinfo=Weainfo; [Self givevalue]; }];}- (void) givevalue{Self.city.text=self.weatherInfo.city; Self.date.text=self.weatherInfo.date; Self.week.text=Self.weatherInfo.week; Self.wind.text=Self.weatherInfo.wind; Self.weather.text=Self.weatherInfo.weather; Self.tips.text=Self.weatherInfo.tip; Self.tips.userInteractionEnabled=NO;}
The class I encapsulated can go to my github fetch: Https://github.com/wangdachui
IOS self-encapsulated network requests, JSON-parsed classes