Ios_21 buy-through block to the request tool class Proxy method to carry out two times encapsulation

Source: Internet
Author: User

Eventually:



" reviews " provided by the tool class DPAPI after the request is complete, the proxy mechanism is used, and when a request succeeds or fails, the corresponding method of the proxy is invoked


In order to encapsulate the tool-class DPAPI provided by the reviews two times,

Once again, a block is defined:

typedef void (^requestdonecallbackblock) (ID deals,nserror *err);

The block has two parameters,

The server returns an array of deals dictionaries, respectively, when successful

Another parameter is: When the request fails, the server returns a failure message

Two parameters corresponding to the agent's two methods (that is, the proxy method that was called separately for success and failure)


The Block invocation time is:

After a DPAPI request is completed , the block is called in the Proxy method, regardless of the failure and success.

The request result of the request is passed back to the tool class,

Within the tool class, the return result is judged

And then decide whether to call the external successblock or Failblock


This block is corresponding to a request and is stored in the member dictionary,

To handle concurrent requests , ensure that one request corresponds to the callback block One by one of a request result


Tool Class:

DealRequestTool.h

  dealrequesttool.h//  Handsome _ buy////  Created by Beyond on 14-8-19.//  Copyright (c) 2014 Com.beyond. All rights reserved.//  , use two block encapsulation to send all the requested code to the server #import <foundation/foundation.h>//define the block that was called after the request was successful, Returns a typedef void (^successblock) (Nsarray *deals) after the dictionary array returned by the server is converted to an array of objects,  and/or block that is called after the request fails, returning the error message returned by the server to typedef void (^failblock) (Nserror *error); @interface dealrequesttool:nsobjectsingleton_interface (Dealrequesttool)//object method, which internally encapsulates a dictionary of parameters submitted to the server ( Obtained from the tool Class), and by invoking a custom method, use two blocks to encapsulate the agent method of DPAPI-(void) 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.//single case, use two times block encapsulation to send all the requested code to the server #import "DealRequestTool.h" #import "MetaDataTool.h" #import "City.h "#import" DPAPI.h "#import" Deal.h "#import" Order.h "//important, define a block that is called in the proxy method once the DPAPI request is complete, regardless of the failure and success, this block corresponds to a request, Save in a member dictionary, to ensure that the callback block one by one corresponds to a typedef void (^requestdonecallbackblock) (ID deals,nserror *err) for a request and a request result when concurrency is processed; @ Interface Dealrequesttool () <dprequestdelegate>{//important, each request, corresponds to a requestdonecallbackblock, and in the agent method of DPAPI, At the end of the request, call the success or failure information of the Requestdonecallbackblock callback server, because only one initialization is required, nsmutabledictionary *_requestblockdict in the Init method;}        @end @implementation dealrequesttoolsingleton_implementation (dealrequesttool)-(ID) init{if (self = [super init]) { Important, each request, corresponding to a requestblock, and in the proxy method calls the Requestblock callback server's success or failure information, simply initialize once, in the init method _requestblockdict = [nsmutable    Dictionary Dictionary]; } return self;} 1. Object method for external invocation. The parameter dictionary (obtained from the tool class) that was submitted to the server is internally encapsulated andUsing a custom method, two blocks were used to encapsulate the agent method of DPAPI-(void) Dealrequestwithpageno: (int) PageNo success: (Successblock) Successbock fail: (    Failblock) failblock{nsmutabledictionary *paramsdict = [Nsmutabledictionary dictionary];    1. Obtain all the request parameters from the tool class, i.e. the current city, quotient area, sorting, etc. [Paramsdict addentriesfromdictionary:[self getallrequestparamsdict];            1.1. Add page number parameter (int to string) [Paramsdict setobject:@ (PageNo) forkey:@ "page"]; 2. Important ~ ~ ~ ~ Call the custom method, 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 successful dictionary array and the failure information for this request//Now only need to judge, the request callback block has no successful return results, if there is, and the external caller needs the result before the corresponding request result is called back again to the outside if (deals) {if (Successbock) {Nsmutablea                Rray *dealsarr = [Nsmutablearray array];                From the returned results according to Key, take out all the dictionary array, one by one times the calendar, turn into model nsarray *arr = deals[@ "Deals"]; For (Nsdictionary *dict in arr) {Deal *deal = [[Deal alloC]init];                    [Deal setvalueswithdict:dict];                [Dealsarr Addobject:deal];            }//callback The encapsulated model array to the outside caller (lattice display data) Successbock (Dealsarr);                }} else {//Also, the requested callback block has no failed information, if any, and the external caller needs the result, the corresponding request result is again returned to the external if (Failblock) {            Failblock (ERR);        }        }                    }]; }//the custom method, pinch all request parameters from the tool class-(Nsdictionary *) getallrequestparamsdict{nsmutabledictionary *params = [Nsmutabledictionary di    Ctionary];    1.1. Add City parameter NSString *city = [Metadatatool sharedmetadatatool].currentcity.name;        [Params setobject:city forkey:@ "City"];    1.2. Add Zone parameter NSString *district = [Metadatatool sharedmetadatatool].currentdistrictname; if (District &&![    District Isequaltostring:kalldistrict]) {[Params setobject:district forkey:@ "region"]; }//1.3. Add categorical parameters nsstring *category = [Metadatatool sharedmetadatatool].currentcateGoryname; if (category &&![    Category Isequaltostring:kallcategory]) {[Params setobject:category forkey:@ "category"];    }//1.4. Add Sort parameter Order *order = [Metadatatool sharedmetadatatool].currentorder;    if (order) {//by other means [params setobject:@ (Order.index) forkey:@ "Sort"]; } return params; 2. Call the custom method, send the DPAPI request, and after the DPAPI request ends, call the corresponding requestdonecallbackblock-(void) Requestwithurl for this request in the Proxy method: (NSString *)    URL params:params requestblock: (requestdonecallbackblock) callbackblock{DPAPI *api = [DPAPI Shareddpapi]; Important ~ ~ ~ must return the dprequest of this request, and corresponding to requestblock one by one, in the dictionary, because of the possibility of concurrent requests, if not the callback Requestblock and dprequest one by one corresponding to the case,    The result of the next request overwrites the situation where the last request occurred dprequest *dprequest= [API Requestwithurl:url params:params delegate:self]; Important ~ ~ ~ with the member variable _requestblockdict remember this request, and the corresponding callback Requestblock, in the proxy method can be removed from the dictionary, set the callback block parameters (_deals or error message) [_ Requestblockdict setobject:callbackblock forKey:dpRequest.description];} #pragma mark-Proxy method//Called when a request succeeds, parameter: The request object of the request, the requestRequested result-(void) Request: (Dprequest *) Request Didfinishloadingwithresult: (ID) result{//first from the member dictionary, according to the requested object,    Remove the callback for this request block requestdonecallbackblock Callbackblock = [_requestblockdict objectForKey:request.description]; Direct callback to the block corresponding to this request, and the request result (deals dictionary array) callback, because this proxy method is called when the request is successful, so callback block failure parameters do not fill callbackblock (Result,nil);} Call when a request fails, parameter: Request object for the request, reason for failure of the request-(void) Request: (Dprequest *) Request Didfailwitherror: (Nserror *) error{//first from the member dictionary , according to this request object, take out the callback block requestdonecallbackblock callbackblock = [_requestblockdict objectforkey:    Request.description]; Direct callback to the block corresponding to this request, and the reason for the failure callback, because this agent method is called when the request failed, so callback block's success parameter does not fill Callbackblock (Nil,error);} @end

External callers: That is, the controller

Deallistcontroller.m

deallistcontroller.m//Handsome _ buy////Created by Beyond on 14-8-14.//Copyright (c) 2014 Com.beyond. All rights reserved.//Click on the dock above the "buy" button corresponding to the controller, above the navigation bar, the right side of the navigation bar is Searchbar, the left side of the navigation bar is a large button (Topmenu) (the interior consists of three small buttons < topmenuitem>) #import "DealListController.h"//The left side of the navigation bar is a large button (top menu) #import "TopMenu.h"//Encapsulated Custom Cell#import " DealCell.h "//reviews provided encapsulation of sending request class #import" DPAPI.h "//Tool class #import" MetaDataTool.h "//Package Request Tool Class #import" DealRequestTool.h "// Model class #import "City.h" #import "Deal.h" #define KITEMW 250#define kitemh 250@interface deallistcontroller () < dprequestdelegate>{//used to receive the dictionary array returned by the server----converted into an array of objects for the lattice to display Nsmutablearray *_deals;} @end @implementation deallistcontroller//Override Controller Init method-(ID) init{//Create a flow layout uicollectionviewflowlayout *layout = [U    Icollectionviewflowlayout alloc] init];        Set the flow layout inside each grid width and height, that is, the size of each grid layout.itemsize = Cgsizemake (KITEMW, KITEMH); Call the Initwithcollectionviewlayout method of the parent class Uicollectionviewcontroller, (self is not found here, will go to the parent class to find the method) return [self InitwithcollectionViewlayout:layout];}    -(void) viewdidload{[Super Viewdidload];    _deals = [Nsmutablearray array];        0. Monitor all changes (e.g. city, quotient, classification, sort) kaddallnotes (datachanged)//1. Basic settings for the top navigation bar [self setnavigationbar]; Basic settings for 2.collectionView [self setcollectionview];} 0. When listening to changes such as the city, make a request to the server-(void) datachanged{///critical ~~~~~ call encapsulate the Request tool class, send the request, parameters: number of pages, [[Dealrequesttool Shareddealrequesttoo            L]dealrequestwithpageno:1 success:^ (Nsarray *deals) {//Remove old data first [_deals removeallobjects];            Then add the encapsulated object array to the member variable [_deals addobjectsfromarray:deals];    Next, we can provide the data source for CollectionView [Self.collectionview Reloaddata];    } fail:^ (Nserror *error) {log (@ "Request---fail:%@", error); }];}    2. Basic settings of the top navigation bar-(void) setnavigationbar{//1. The search box on the right Uisearchbar *s = [[Uisearchbar alloc] init];    S.frame = CGRectMake (0, 0, 210, 35);    S.placeholder = @ "Please enter product name, address, etc."; Self.navigationItem.rightBarButtonItem = [[UibarbuttonitemAlloc] initwithcustomview:s];    2. Left menu bar Topmenu *top = [[Topmenu alloc] init]; Important, Topmenu inside the item clicked, the created Popmenu will be added to where to go???    is the view Top.controllerview = Self.view of this controller;        Self.navigationItem.leftBarButtonItem = [[Uibarbuttonitem alloc] initwithcustomview:top]; }//3.collectionView Basic Settings-(void) setcollectionview{//1. Set the background color of the CollectionView (unlike Tableviewcontroller,        The view of the controller is UIView, added in the UIView collectionview) Self.collectionView.backgroundColor = KGLOBALBG; 2. Xib [Self.collectionview registernib:[uinib nibwithnibname:@ "Mydealcell" bundle:nil] to be used for registering the cell        forcellwithreuseidentifier:@ "Dealcell"];    3. Set CollectionView to always support vertical scrolling, ready for pull-down refresh (Spring) self.collectionView.alwaysBounceVertical = YES; }//4. Important ~ ~ ~ because when the controller is created, the width default is 768, the high default is 1024, regardless of the screen//only in the Viewwillappear and Viewdidappear methods, you can get the view the most accurate (that is, the actual) Width and height (width and height)-(void) Viewwillappear: (BOOL) animated{//default calculation layout [self didrotatefrominterfaceorientation:0];} #pragma mark-Parent class method//intercept, the screen is about to be rotated when called (control(void) Willrotatetointerfaceorientation: (uiinterfaceorientation) tointerfaceorientation Duration: ( Nstimeinterval) duration{Log (@ "screen is about to rotate");} Intercept, when screen rotation is complete, call-(void) Didrotatefrominterfaceorientation: (uiinterfaceorientation) frominterfaceorientation{//1. Remove the uicollectionviewflowlayout uicollectionviewflowlayout *layout = (Collectionviewcontroller) that was passed in when creating the            Uicollectionviewflowlayout *) Self.collectionView.collectionViewLayout;    2. Calculate the spacing 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)) {//cross-screen spacing v = (height-2 * KItem        H)/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 squares of the animation [UIView animatewithduration:4.0 animations:^{//Margin layout.secti in the upper left and right four directionsOninset = Uiedgeinsetsmake (H, H, V, h);    The spacing between each line layout.minimumlinespacing = h; }];} #pragma Mark-collectionview Proxy method//Total number of item (that is, Lattice cube)-(Nsinteger) CollectionView: (Uicollectionview *) CollectionView numberofitemsinsection: (nsinteger) section{return _deals.count;} Generate each unique lattice-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (    Nsindexpath *) indexpath{static NSString *cellid = @ "Dealcell";        Dealcell *cell = [CollectionView dequeuereusablecellwithreuseidentifier:cellid Forindexpath:indexpath];    Set unique data Cell.deal = _deals[indexpath.row];  returns cell return cell; <span style= "White-space:pre" ></span> @end









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.