IOS_21 group_use block to encapsulate the proxy method of the Request tool class. ios_21block

Source: Internet
Author: User

IOS_21 group_use block to encapsulate the proxy method of the Request tool class. ios_21block

Finally:



[Comment] The provided tool DPAPI uses a proxy mechanism after the request is complete. When a request succeeds or fails, the corresponding method of the proxy is called.


To encapsulate the tool DPAPI provided by the comments,

Define a block again:

Typedef void (^ RequestDoneCallBackBlock) (id deals, NSError * err );

The block has two parameters,

The first parameter is the deals dictionary array returned by the server when the request succeeds.

The second parameter indicates the failure message returned by the server when the request fails.

The two parameters correspond to the two methods of the proxy respectively (that is, the proxy methods called upon success or failure)


When the block is called:

After a DPAPI request is completed, you must call the block in the proxy method for both failed and successful requests,

Return the request result of this request to the tool class,

The tool class further judges the return result,

Then decide whether to call external successBlock or failBlock


This block corresponds to a request and is saved to the member dictionary,

The purpose is to ensure that a request exactly corresponds to the callback block of a request result when processing concurrent requests.


Tool class:

DealRequestTool. h

//// DealRequestTool. h // handsome guy _ buy /// Created by beyond on 14-8-19. // Copyright (c) 2014 com. beyond. all rights reserved. // For a Singleton, use a secondary block to encapsulate all the codes that send requests to the server # import <Foundation/Foundation. h> // define the block called after the request is successful. Convert the dictionary array returned by the server into an object array and return the typedef void (^ successBlock) (NSArray * deals ); // define the block called after the request fails, and return the error message returned by the server to typedef void (^ failBlock) (NSError * error); @ interface DealRequestTool: NSObjectsingleton_interface (DealRequestTool) // object method, which encapsulates the parameter dictionary submitted to the server (obtained from the tool class), calls a custom method, and uses a second block to encapsulate the proxy method (void) of DPAPI) dealRequestWithPageNo :( int) pageNo success :( successBlock) successBock fail :( failBlock) failBlock; @ end

Tool class:

DealRequestTool. m

//// DealRequestTool. m // handsome _ buy /// Created by beyond on 14-8-19. // Copyright (c) 2014 com. beyond. all rights reserved. // For The Singleton, use the second block to encapsulate all the code that sends the request to the server # import "DealRequestTool. h "# import" MetaDataTool ool. h "# import" City. h "# import" DPAPI. h "# import" Deal. h "# import" Order. h "// important. After defining a DPAPI request, no matter the request fails or succeeds, the block will be called in the proxy method. This block corresponds to a request and is saved in the member dictionary, the purpose is to ensure that a request and the callback block of a request result correspond to typedef void (^ RequestDoneCall BackBlock) (id deals, NSError * err); @ interface DealRequestTool () <DPRequestDelegate> {// important. Each request corresponds to a RequestDoneCallBackBlock. In the DPAPI proxy method, after the request is complete, call RequestDoneCallBackBlock to return the success or failure information of the server. Because only one Initialization is required, the Init method NSMutableDictionary * _ requestBlockDict;} @ end @ implementation failed (DealRequestTool) -(id) init {if (self = [super init]) {// important. Each request corresponds to a requestBlock and is called in the proxy method. RequestBlock returns the server's success or failure information only once. In the Init method _ requestBlockDict = [NSMutableDictionary dictionary];} return self;} // 1. object method for external calls. the parameter dictionary submitted to the server is encapsulated internally (obtained from the tool class), and The DPAPI proxy method-(void) dealRequestWithPageNo :( int) is encapsulated by calling a custom method and using a secondary block) pageNo success :( successBlock) successBock fail :( failBlock) failBlock {NSMutableDictionary * paramsDict = [NSMutableDictionary dictionary]; // 1. obtain all request parameters from the tool class, that is, the current city, business district, sorting, and other [paramsDic T addEntriesFromDictionary: [self getAllRequestParamsDict]; // 1. 1. add the page number parameter (int to string) [paramsDict setObject: @ (pageNo) forKey: @ "page"]; // 2. important ~~~~ Call the custom method and send the DPAPI request [self requestWithUrl: @ "v1/deal/find_deals" params: paramsDict requestBlock: ^ (id deals, NSError * err) {// here, you can get the callback block corresponding to this request. The parameter already contains the success dictionary array and Failure Information of this request. // now you only need to judge, whether the callback block of the request has successfully returned results. if yes, and the external caller needs the results, the corresponding request results will be called back to the external if (deals) {if (successBock) again) {NSMutableArray * dealsArr = [NSMutableArray array]; // retrieve all dictionary arrays from the returned results according to the Key and traverse them one by one, convert to model NSArray * arr = deals [@ "deals"]; for (NSDic Tionary * dict in arr) {Deal * deal = [[Deal alloc] init]; [deal setValuesWithDict: dict]; [dealsArr addObject: deal];} // call back the encapsulated model array to the external caller (display data in the grid) successBock (dealsArr) ;}} else {// Similarly, whether the request callback block has failed, if yes, and the external caller needs a result, the corresponding request result will be called back to the external if (failBlock) {failBlock (err) ;}}}];} // custom method. obtain all the request parameters from the tool class-(NSDictionary *) getAllRequestParamsDict {NSMutableDictionary * params = [NSMutableDictionary di Ctionary]; // 1. 1. add the city parameter NSString * city = [MetaDataTool ool sharedMetaDataTool ool]. currentCity. name; [params setObject: city forKey: @ "city"]; // 1. 2. add the region parameter NSString * district = [MetaDataTool ool sharedMetaDataTool ool]. currentDistrictName; if (district &&! [District isEqualToString: kAllDistrict]) {[params setObject: district forKey: @ "region"];} // 1. 3. add the category parameter NSString * category = [MetaDataTool ool sharedMetaDataTool ool]. currentCategoryName; if (category &&! [Category isEqualToString: kAllCategory]) {[params setObject: category forKey: @ "category"];} // 1. 4. add the sorting parameter Order * order = [MetaDataTool ool sharedMetaDataTool ool]. currentOrder; if (order) {// sort [params setObject: @ (order. index) forKey: @ "sort"];} return params;} // 2. call a custom method and send a DPAPI request. After the DPAPI request is completed, the request requestDoneCallBackBlock-(void) requestWithUrl :( NSString *) url params: params requestBlo will be called in the proxy method. Ck :( RequestDoneCallBackBlock) callBackBlock {DPAPI * api = [DPAPI sharedDPAPI]; // important ~~~ The DPRequest of this request must be returned, which corresponds to requestBlock one by one and stored in the dictionary, because concurrent requests may occur. If the callback requestBlock and DPRequest are not matched one by one, DPRequest * dpRequest = [api requestWithURL: url params: params delegate: self]; // important ~~~ Use the member Variable _ requestBlockDict to remember this request and the corresponding callback requestBlock. In the proxy method, you can retrieve it from the dictionary and set the callback block parameter (_ deals or error message) [_ requestBlockDict setObject: callBackBlock forKey: dpRequest. description] ;}# pragma mark-proxy method // called when a request is successful. Parameter: The request object of the request, the request result of the request-(void) request :( DPRequest *) request didFinishLoadingWithResult :( id) result {// retrieve the callback block RequestDoneCallBackBlock callBackBlock = [_ requestBlockDict objectForKey: request. description]; // directly calls back the block corresponding to this request and returns the request result (deals dictionary array), because this proxy method is called when the request is successful, therefore, the callback block failure parameter is not set to callBackBlock (result, nil);} // called when a request fails. Parameter: The request object of the request, the cause of the request failure-(void) request :( DPRequest *) request didFailWithError :( NSError *) error {// first from the member dictionary, according to the request object, retrieve the callback block RequestDoneCallBackBlock callBackBlock = [_ requestBlockDict objectForKey: request. description]; // directly calls back the block corresponding to this request and returns the cause of failure because this proxy method is called when the request fails, therefore, callBackBlock (nil, error) is not filled in as the success parameter of the callback block;} @ end

External Caller: Controller

DealListController. m

//// DealListController. m // handsome _ buy /// Created by beyond on 14-8-14. // Copyright (c) 2014 com. beyond. all rights reserved. // click the Controller corresponding to the group purchase button on the dock. The navigation bar is displayed on the top, the searchBar is displayed on the right, and a large button (TopMenu) is displayed on the left of the navigation bar) (It consists of three buttons internally <TopMenuItem>) # import "DealListController. h "// There is a big button (top menu) # import" TopMenu on the left of the navigation bar. h "// encapsulated custom cell # import" DealCell. h "// reviews the class provided to encapsulate and send requests # import" DPAPI. h "// tool class # import" MetaDataTool ool. h "// encapsulate the requested tool class # import" D EalRequestTool. h "// model class # import" City. h "# import" Deal. h "# define kItemW 250 # define kItemH 250 @ interface DealListController () <DPRequestDelegate >{// dictionary array used to receive the server's return ---- array of converted objects, for the grids to display NSMutableArray * _ deals;} @ end @ implementation DealListController // overwrite the Controller's init method-(id) init {// create a stream layout: UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init]; // set the size and height of each grid in the stream layout, that is, layout. ite MSize = CGSizeMake: layout];}-(void) viewDidLoad {[super viewDidLoad]; _ deals = [NSMutableArray array]; // 0. listen to all changed notifications (such as cities, business areas, categories, and sorting) kAddAllNotes (dataChanged) // 1. basic settings in the top navigation bar [self setNavigationBar]; // 2. basic settings of collectionView [self setCollectionView];} // 0 When listening for changes to the city, send a request to the server-(void) dataChanged {// important ~~~~~ Call the encapsulated request tool class and send the request. Parameter: page number, [[DealRequestTool sharedDealRequestTool] dealRequestWithPageNo: 1 success: ^ (NSArray * deals) {// first remove the old data [_ deals removeAllObjects]; // then add the encapsulated object array to the member variable [_ deals addObjectsFromArray: deals]; // you can provide the data source [self. collectionView reloadData];} fail: ^ (NSError * error) {log (@ "request --- fail: % @", error) ;}];} // 2. basic settings in the top navigation bar-(void) setNavigationBar {// 1. UISearchB in the search box on the right Ar * s = [[UISearchBar alloc] init]; s. frame = CGRectMake (0, 0,210, 35); s. placeholder = @ "Enter product name, address, etc."; self. navigationItem. rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: s]; // 2. topMenu * top = [[TopMenu alloc] init]; // important: After you click the item in TopMenu, where will the created PopMenu be added ??? Is the view top of the controller. controllerView = self. view; self. navigationItem. leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: top];} // 3. basic settings of collectionView-(void) setCollectionView {// 1. set the background color of the collectionView (unlike tableViewController, the view of this controller is UIView, And the collectionView added in the UIView) self. collectionView. backgroundColor = kGlobalBg; // 2. the xib [self. collectionView registerNib: [UINib nibWithNibNa Me: @ "MyDealCell" bundle: nil] forCellWithReuseIdentifier: @ "DealCell"]; // 3. sets collectionView to always support vertical scrolling and prepares (spring) self for pull-down refresh. collectionView. alwaysBounceVertical = YES;} // 4. important ~~~ When the controller is created, the default width is 768 and the default height is 1024. no matter whether the screen is horizontal or vertical, the view can be obtained most accurately (that is, the actual view) only in the viewWillAppear and viewDidAppear methods) width and height (width and height)-(void) viewWillAppear :( BOOL) animated {// default calculation layout [self didRotateFromInterfaceOrientation: 0];} # pragma mark-parent class method // interval, called when the screen is about to rotate (Controller monitoring screen rotation)-(void) willRotateToInterfaceOrientation :( UIInterfaceOrientation) toInterfaceOrientation duration :( NSTimeInterval) duration {log (@ "the screen is about to rotate");} // intercept, call-(void) didRotateFromInterfaceOrientation (UIInterfaceOrientation) fromInterfaceOrientation {// 1. retrieve the UICollectionViewFlowLayout * layout = (UICollectionViewFlowLayout *) self. collectionView. collectionViewLayout; // 2. calculation interval CGFloat v = 0; CGFloat h = 0; CGFloat height = self. view. frame. size. height-44; CGFloat width = self. view. frame. size. width; if (UIInterfaceOrientationIsLandscape (self. interfaceOrientation) {// horizontal screen spacing v = (height-2 * kItemH)/3; h = (width-3 * kItemW)/4 ;} else {// vertical screen spacing v = (height-3 * kItemH)/4; h = (width-2 * kItemW)/3;} // 3. adjust the distance between the grids in the animation [UIView animateWithDuration: 4.0 animations: ^ {// margin layout in the upper left and lower right directions. sectionInset = UIEdgeInsetsMake (h, h, v, h); // layout. minimumLineSpacing = h ;}] ;}# pragma mark-collectionView proxy method // Total number of items (I .e., the grid Cube)-(NSInteger) collectionView :( UICollectionView *) collectionView numberOfItemsInSection :( NSInteger) section {return _ deals. count;} // generate each unique grid-(UICollectionViewCell *) collectionView :( UICollectionView *) collectionView cellForItemAtIndexPath :( NSIndexPath *) indexPath {static NSString * cellID = @ "DealCell "; dealCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier: cellID forIndexPath: indexPath]; // set a unique data cell. deal = _ deals [indexPath. row]; // return cell;} @ end












Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.