Mobile development on the road--iOS mobile Development Series Network Interaction Four (2)

Source: Internet
Author: User
Tags allkeys

And then last time, this time we talk about the encapsulation of the network request open the created project, let's go ahead and finish him,

First, let's create a nsobject file.

Be careful to circle the light. Don't be mistaken.

Once created, start writing code,

First of all, we don't have to cite the project file.

Look at the picture

Let's define the interface and a block

// Block Definition void (^requestfinishblock) (ID result);

1 @interfaceZwjdataservice:nsobject2 3 //Defining Interfaces4+ (ASIHTTPRequest *) Requestwithurl: (NSString *) urlstring5                            params:(Nsmutabledictionary *)params6HttpMethod: (NSString *) HttpMethod7 Completeblock: (requestfinishblock) block;8 9 @end

Chip

Open a. m file

Add to that because we have the network data in JSON format, so we have to parse the JSON and refer to the third-party library,

Jsonkit

Import JSONkit.h jsonkit.m two files first

Cocoa has a lot of JSON open-source class libraries, and the Jsonkit library is very easy to use and efficient and relatively high.

To use the Jsonkit library to parse the JSON file, just download JSONKit.h and JSONKIT.M to the project (download link), then add Libz.dylib to

In the extension, talk about how to use

1. Convert JSON to Nsdictionary

NSString *string@ "{\"name\": \" My name\ ", \" list\ ": [\" one\ ", \" \ ", \" Three\ "]}";       NSData* Jsondata = [string  datausingencoding:nsutf8stringencoding];       

2. Convert Nsdictionary to JSON-formatted string

// Resultsdic is a dictionary  that needs to be converted NSString *String

Continue to return to the topic below

implementing interfaces defined in. h files

+ (ASIHTTPRequest *) Requestwithurl: (NSString *) urlstring                           params:(nsmutabledictionary *)  params                       *) HttpMethod                    completeblock: (requestfinishblock) block{}

The parameters of this method I do not make comments I think we can understand the meaning of the word as well. Before the English did not learn, now learning programming also to help learn Chinese ...

We're going to do one more thing. Define a macro-base address

It means that we have to access the interface must use the URL, then the URL will certainly have a host address and interface of the main entrance is constant, the side of things need our dynamic to load, change.

#define Base_url @ "http://**********/api/"

Here my test address will not be shown, you can also according to their own different needs to define their own interface body

My URL here is divided into

Body Part + token + other parameter combination

Other parameters: We have defined in the interface that he is a nsmutabledictionary type, in C # is a Dictionary of dictionary key-value pairs

params:(nsmutabledictionary *)params

Here we have to obey the rules of OC in order to define the parameters;

Stitching URL String

// stitching URL string    Urlstring=[base_url Stringbyappendingformat:@ "%@?access_token=aa", urlstring];        NSLog (@ "", urlstring);

Stitching completed, we to verify whether the correct printing, look at the output of our interface to the consistency of the corresponding response;

Next, we want to determine whether the request is get or POST

We're using caseinsensitivecompare here, so just talk about Caseinsensitivecompare here.

NSString *astring01 = @ "GET";
NSString *astring02 = @ "Get";
BOOL result = [Astring01 compare:astring02] = = Nsorderedsame;
NSLog (@ "result:%d", result);
Nsorderedsame determines whether the contents of the two are the same ignore case

The string of Get request should be stitched up below;

//parameters for processing get requestsNscomparisonresult Comparret1=[httpmethod Caseinsensitivecompare:@"GET"]; if(comparret1==nsorderedsame) {nsmutablestring*paramsstring=[nsmutablestringstring]; Nsarray*allkeys=[paramsAllKeys]; NSLog (@"parms:%@ \ r \ n",params);  for(intI=0; i<params. Count; i++) {NSString*key=[AllKeys objectatindex:i]; IDvalue=[paramsObjectforkey:key]; [Paramsstring AppendFormat:@"%@=%@", Key,value]; if(i<params. count-1) {[paramsstring AppendFormat:@"&"]; } NSLog (@"paramsstring:%@", paramsstring); }                if(paramsstring.length>0) {urlstring=[urlstring Stringbyappendingformat:@"&%@", paramsstring]; }} Nsurl*url=[Nsurl urlwithstring:urlstring]; NSLog (@"URL:%@", URL);

After you finish printing, check that the string is correct

Today first to talk about here, it's time to go to bed, thank you for my support, attention!

If you feel useful, do not forget to recommend Oh, common learning, common progress!

Zhangwenjian
Source: Http://www.cnblogs.com/zhangwenjian
The copyright of this article is owned by the author, welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
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.