Before introducing a small project, here is a description of this code is not written by me, I am just a collation of the essay.
Let's show it before the introduction.
See everyone should be very familiar with, is hungry of an interface just, it is worth noting that the implementation is not a local connection, but real deal network connection. Look at the file schema.
This is the MVC design pattern, although the file is very small, but can also be seen.
The following is a formal introduction to the implementation of small projects.
First of all, the implementation of model, very simple, the implementation of models can be,
Shop.h
shop.h// cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.// Copyright 2016 Xubaoaichiyu. All rights reserved.//#import <Foundation/Foundation.h> @interface shop:nsobject//Build Shop model @property (nonatomic , copy) NSString * address, @property (nonatomic, copy) NSString * name; @property (nonatomic, copy) NSString * image_path;/ /-description This method system occupies @property (nonatomic, copy) NSString * DESC; @end
shop.m
shop.m// cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.// Copyright 2016 Xubaoaichiyu. All rights reserved.//#import "Shop.h" @implementation shop@end
Model implementation After we do not have a real implementation method, the following is not, next is the encapsulation of AFN, the reason is encapsulated because, we can not guarantee in the future that the three parties can still exist, as long as the package, even if there is no AFN in the packaging framework of the use of other three-party implementation.
HttpClient.h HTTPCLIENT.M
httpclient.h//cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.//Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import <Foundation/Foundation.h> #import "AFNetworking.h"//http request category typedef ns_enum ( Nsinteger,httprequesttype) {httprequestget, httprequestpost, Httprequestput, httprequestdelete,};/** * prior to request Block */typedef Void (^prepareexecuteblock) (void); typedef void (^successblock) (Nsurlsessiondatatask * task, ID Responseobject); typedef void (^failureblock) (Nsurlsessiondatatask * task, Nserror * error); @interface HttpClient: nsobject+ (HttpClient *) defaultclient;/** * HTTP request (get,post,put,delete) * * @param URL Request Address * @param method Request Type * @param params Request parameter * @param prepare pre-Request preprocessing * @param success Request successfully processed * @param failure request failed processing */-(void) Requestwithpath :(NSString *) URL method: (Nsinteger) method paramenters: (Nsdictionary *) params Prepareexe Cute: (prepareexecuteblock) Prepare success: (SuccessBlock) Success failure: (Failureblock) failure; @end
httpclient.m//cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.//Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import "HttpClient.h" @interface HttpClient () @property (nonatomic, Strong) Afhttpsessionmanager * Manager; @property (nonatomic, assign) BOOL isconnect; @end @implementation httpclient-(instancetype) init{self = [supe R Init]; if (self) {self.manager = [Afhttpsessionmanager manager]; Set Request Type Self.manager.requestSerializer = [Afhttprequestserializer serializer]; Set Response Type Self.manager.responseSerializer = [Afjsonresponseserializer serializer]; Self.manager.responseSerializer.acceptableContentTypes = [Nsset setwithobjects:@ "Application/json", @ "text/html", @ "Text/json", @ "Text/javascript", @ "Text/plain", @ "Image/gif", nil]; Turn on listening [self opennetmonitoring]; } return self;} Determine if there is an Internet connection and have a network connection to proceed to the next operation. -(void) opennetmonitoring {[[Afnetworkreachabilitymanager SHaredmanager] setreachabilitystatuschangeblock:^ (afnetworkreachabilitystatus status) {switch (status) { Case AFNetworkReachabilityStatusUnknown:self.isConnect = NO; Break Case AFNetworkReachabilityStatusNotReachable:self.isConnect = NO; Break Case AFNetworkReachabilityStatusReachableViaWiFi:self.isConnect = YES; Break Case AFNetworkReachabilityStatusReachableViaWWAN:self.isConnect = YES; Break Default:break; } }]; [[Afnetworkreachabilitymanager Sharedmanager] startmonitoring]; Self.isconnect = YES;} Singleton + (HttpClient *) defaultclient {static HttpClient * instance = nil; Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{instance = [[Self alloc] init]; }); return instance;} -(void) Requestwithpath: (Nsstring *) URL method: (Nsinteger) method paramenters: (Nsdictionary *) params prepareexecute: (Pr Epareexecuteblock) Prepare success: (Successblock) Success failure: (Failureblock) Failure { if ([self isconnectionavailable]) {//preprocessing if (prepare) {prepare (); } switch (method) {case httprequestget: [Self.manager get:url Parameters:params Progress:nil success:success Failure:failure]; Break Case Httprequestpost: [Self.manager post:url parameters:params progress:nil success:success failure:failure ]; Break Case Httprequestput: [Self.manager put:url parameters:params success:success failure:failure]; Break Case Httprequestdelete: [Self.manager delete:url parameters:params success:success failure:failure]; Break Default:break; }} else {[self showexceptiondialog]; }}-(BOOL) isconnectionavailable {return self.isconnect;} If, without the network, eject alert-(void) Showexceptiondialog {[[[[Uialertview alloc] initwithtitle:@ "Prompt" message:@ "Network connection exception, check the network connection" Delegate:nil cancelbuttontitle:@ "Good" otherbuttontitles:nil) show];} @end
The next step is to encapsulate the Svprogresshud
TollHeper.h TOLLHEPER.M
toolhelper.h// cx-Small Project (hungry for a simple implementation of the network)//// Created by Ma C on 16/3/23.// Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import <Foundation/Foundation.h> @interface toolhelper:nsobject/******************* Indicator method ****************///to the indicator, such as the emergence of new mainstream three-party, can be very good upgrade//pop-up Operation error message prompt box + (void) Showerrormessage: (NSString *) message;//Popup Operation success message prompt box + (void) Showsuccessmessage: (NSString *) message;//popup load Prompt box + (void) Showprogressmessage: ( NSString *) message;//Popup user information + (void) Showinfomessage: (NSString *) message;//cancel pop-up box + (void) Dismisshud; @end
toolhelper.m// cx-Small Project (hungry for a simple implementation of the network)//// Created by Ma C on 16/3/23.// Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import "ToolHelper.h" #import "SVProgressHUD.h" @implementation toolhelper//pop-up action error message prompt box + (void) Showerrormessage: (NSString *) message { [Svprogresshud showerrorwithstatus:message]; } Pop-up Operation success message prompt box + (void) Showsuccessmessage: (NSString *) message { [Svprogresshud showsuccesswithstatus:message];} Popup Load Prompt box + (void) Showprogressmessage: (NSString *) message { [Svprogresshud showwithstatus:message]; } Popup User information + (void) Showinfomessage: (NSString *) message { [Svprogresshud showinfowithstatus:message]; } Cancels the popup box + (void) Dismisshud { [svprogresshud dismiss];} @end
After the above work to solve the above is the problem left over, do not know if you have found in the model of the comments
-description This method system occupies
How do we solve this problem, then I would like to say that the three-party.
MJ's three-party solution to the problem
MJExtensionConfig.h MJEXTENSIONCONFIG.M
mjextensionconfig.h// cx-Small Project (hungry for a simple implementation of the network)//// Created by Ma C on 16/3/23.// Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import <Foundation/Foundation.h> @interface mjextensionconfig:nsobject@end
mjextensionconfig.m// cx-Small Project (hungry for a simple implementation of the network)//// Created by Ma C on 16/3/23.// Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import "MJExtensionConfig.h" #import "MJExtension.h" #import "Shop.h" @implementation mjextensionconfig//program startup is bound to call the + (void) load { /** * To resolve the inconsistency between the JSON field of the network and the local model property name * * @ Return to the left is the local property name, the right is the network JSON name */ [shop mj_setupreplacedkeyfrompropertyname:^nsdictionary *{ return @{@ "desc": @ "description"};} ]; } @end
(for load in front of the blog I have a detailed explanation, not clear friends can see)
After processing, in order to facilitate the entire program can be used to optimize the two files, we use PCH file
Eleme.pch
eleme.pch// cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.// Copyright 2016 Xubaoaichiyu. All rights reserved.//#ifndef Eleme_pch#define eleme_pch#ifdef __objc__#import <UIKit/UIKit.h> #import < foundation/foundation.h> #endif #import "ToolHelper.h"/***************server host***************/#define SERVER_ HOST @ "Http://restapi.ele.me/v3"/***************server api***************///get restaurant List # define Api_getrestaurantslist @ "/restaurants" #define Screen_width [UIScreen mainscreen].bounds.size.width#define screen_height [UIScreen mainScreen ].bounds.size.height#define shopinfopagelimit 20#endif/* eleme_pch */
After writing the code, we need to set up
Set the following
In fact, the whole small project is really simple, resulting in nothing to think carefully, write more than just fine.
Here is the main link (the explanatory notes are very detailed, I will not say much nonsense)
ViewController.h VIEWCONTROLLER.M
////viewcontroller.h//cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.//Copyright? 2016 Xubaoaichiyu. A ll Rights reserved.//#import <UIKit/UIKit.h> @interface viewcontroller:uiviewcontroller@end
viewcontroller.m//cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.//Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import "ViewController.h" #import "HttpClient.h" #import "SVProgressHUD.h" #import "Shop.h" # Import "MJExtension.h" #import "ShopIconCell.h" #import "MJRefresh.h" static NSString * identifier = @ "Shopinfocell"; @ Interface Viewcontroller () <uitableviewdatasource,uitableviewdelegate>//number of pages @property (nonatomic, assign) Nsinteger page; @property (nonatomic, Strong) UITableView * TableView; @property (nonatomic, Strong) Nsmutablearray * datal ist; @end @implementation viewcontroller-(Nsmutablearray *) dataList {if (!_datalist) {_datalist = [nsmutabl Earray array]; } return _datalist;} -(UITableView *) TableView {if (!_tableview) {_tableview = [[UITableView alloc] InitWithFrame:self.view.bo Unds Style:uitableviewstyleplain]; _tableview.datasource =self; _tableview.delegate =self; [_tableview registerclass:[Shopinfocell class] forcellreuseidentifier:identifier]; _tableview.rowheight = 80; } return _tableview;} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {return Self.dataList.cou NT;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {Shopinfoce ll * cell = [TableView dequeuereusablecellwithidentifier:identifier]; Cell.shop = Self.datalist[indexpath.row]; return cell;} -(void) viewdidload {[Super viewdidload]; Additional setup after loading the view, typically from a nib. [Self.view AddSubview:self.tableView]; Use Mjrefresh to add a pull-down refresh to our talbleview load control Self.tableView.mj_header = [Mjrefreshnormalheader headerwithrefreshingtarg Et:self refreshingaction: @selector (loadnewdata)]; Self.tableView.mj_footer = [Mjrefreshbacknormalfooter footerwithrefreshingtarget:self refreshingaction: @selector ( Loadmoredata)]; //[Self loadnewdata]; Enter the interface to perform a pull-down Refresh method [Self.tableView.mj_header beginrefreshing]; }//load More-(void) Loadmoredata {NSString * urlstring = [NSString stringwithformat:@ "%@%@", Server_host,api_getre Staurantslist]; Nsdictionary * params = @{@ "Full_image_path": @ "1", @ "Geohash": @ "Wx4u14w0649y", @ "Limit": @ (Shopinfopagelimit), @ "offset": @ (Self.page * shopinfopagelimit), @ "type": @ "Geohash" @ "extras[": @ "Food_activity", @ "extras[]": @ "restaurant_activity"}; [[HttpClient defaultclient] requestwithpath:urlstring method:httprequestget paramenters:params prepareExecute:^{ [Toolhelper showprogressmessage:@ "I am refreshing"]; } success:^ (Nsurlsessiondatatask *task, id responseobject) {NSLog (@ "%@", responseobject); JSON--MODEL has a lot of frames, the principle is KVC. Mjextenstion Jsonmodel Mantle Yymodel//requested paging data +1//When the count value returned to the data is 0 o'clock, the description has been All loads are complete. Nsarray * shoplist = [shop mj_objectarraywithkeyvaluesarray:responseobject]; if (Shoplist.count = = 0) {//////display has been fully loaded//[Self.tableView.mj_f Ooter Endrefreshingwithnomoredata]; } if (Self.page > 2) {[Self.tableView.mj_footer Endrefreshingwithnomor EData]; } else {[self.datalist addobjectsfromarray:shoplist]; [Self.tableview Reloaddata]; Reload the pull-up control [Self.tableView.mj_footer endrefreshing]; Self.page + +; } [Toolhelper showsuccessmessage:@ "request succeeded"]; } failure:^ (Nsurlsessiondatatask *task, Nserror *error) {NSLog (@ "%@", error); Reload the pull-up control [Self.tableView.mj_footer endrefreshing]; [Toolhelper showerrormessage:@ "request Failed"]; }];} Drop-down Refresh-(void) Loadnewdata {NSString * urlstring = [NSString stringwithformat:@ "%@%@", Server_host,api_getrestau Rantslist]; Drop-down refresh, the address of the pull-up load request is the same, but the parameters are not the same. The limit is constant, changing the offset. The drop-down refresh is to load the latest data and page pages to 0. The pull-up load loads more data. page++//mjrefresh Ego drop-down refresh Uirefreshcotrol self write pull down nsdictionary * params = @{@ "Full_image_path": @ "1", @ "Geohash": @ "wx4u14w0649y" @ "Limit": @ (Shopinfopagelimit), @ "offset": @ (0), @ "type": @ "Geohash" @ "extra S[] ": @" food_activity "@" extras[": @" restaurant_activity "}; [[HttpClient defaultclient] requestwithpath:urlstring method:httprequestget paramenters:params prepareExecute:^{ [Toolhelper Showprogressmessage:@ "I am refreshing"]; } success:^ (Nsurlsessiondatatask *task, id responseobject) {NSLog (@ "%@", responseobject); JSON--MODEL has a lot of frames, the principle is KVC. Mjextenstion Jsonmodel Mantle Yymodel//paging data requested +1 Self.page = 1; Delete all previous data before getting the latest data [Self.datalist removeallobjects]; Nsarray * shoplist = [shop mj_objectarraywithkeyvaluesarray:responseobject]; [Self.datalist addobjectsfromarray:shoplist]; [Self.tableview Reloaddata]; Reset no more data (eliminate the state without more data) [Self.tableView.mj_footer Resetnomoredata]; Bounce the drop-down refresh control [Self.tableView.mj_header endrefreshing]; [Toolhelper showsuccessmessage:@ "request Success"]; } failure:^ (Nsurlsessiondatatask *task, Nserror *error) {NSLog (@ "%@", error); Bounce the drop-down refresh control [Self.tableView.mj_header endrefreshing]; [Toolhelper Showerrormessage:@ "request Failed"]; }];} -(void) didreceivememorywarning {[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end
People are not feeling what is missing, of course, the cell's custom, quite simple. Just look.
ShopIconCell.h SHOPICONCELL.M
shopiconcell.h// cx-Small Project (hungry for a simple implementation of the network)//// Created by Ma C on 16/3/23.// Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import <UIKit/UIKit.h> #import <UIKit/UIKit.h> #import "Shop.h" @interface Shopinfocell:uitableviewcell@property (nonatomic, strong) shop * SHOP; @end
shopiconcell.m//cx-Small Project (Hungry Network part simple implementation)////Created by Ma C on 16/3/23.//Copyright? 2016 Xubaoaichiyu. All rights reserved.//#import "ShopIconCell.h" #import "uiimageview+webcache.h" static cgfloat kmargin = 5; @interface Shopinfocell () @property (nonatomic, Strong) Uiimageview * IconView; @property (nonatomic, Strong) UILabel * Namelabel; @pr Operty (nonatomic, Strong) UILabel * Desclabel; @end @implementation shopinfocell-(void) Setshop: (Shop *) Shop {_sho p = shop; [Self.iconview Sd_setimagewithurl:[nsurl URLWithString:shop.image_path] placeholderimage:nil]; Self.nameLabel.text = Shop.name; Self.descLabel.text = Shop.desc;} -(Uiimageview *) IconView {if (!_iconview) {_iconview = [[Uiimageview alloc] init]; } return _iconview;} -(UILabel *) Namelabel {if (!_namelabel) {_namelabel = [[UILabel alloc] init]; } return _namelabel;} -(UILabel *) Desclabel {if (!_desclabel) {_desclabel = [[UILabel alloc] INIT]; } return _desclabel;} -(Instancetype) Initwithstyle: (Uitableviewcellstyle) style Reuseidentifier: (NSString *) Reuseidentifier {if (self = [ Super Initwithstyle:style Reuseidentifier:reuseidentifier]) {[Self.contentview AddSubview:self.iconView]; [Self.contentview AddSubview:self.nameLabel]; [Self.contentview AddSubview:self.descLabel]; } return self;} -(void) layoutsubviews {[Super layoutsubviews]; Self.iconView.frame = CGRectMake (Kmargin, Kmargin, 70, 70); Self.nameLabel.frame = CGRectMake (Cgrectgetmaxx (self.iconView.frame) + Kmargin, Cgrectgetminy (Self.iconView.frame), Screen_width-cgrectgetmaxx (Self.iconView.frame)-2 * kmargin, 20); Self.descLabel.frame = CGRectMake (Cgrectgetminx (Self.nameLabel.frame), Cgrectgetmaxy (self.nameLabel.frame) + Kmargin, Cgrectgetwidth (self.nameLabel.frame), 20); }-(void) awakefromnib {}-(void) setselected: (BOOL) selected animated: (bool) animated {[SuperSetselected:selected animated:animated]; } @end
Just such a small project is done.
ios-Small Project (Hungry network part of the simple implementation)