AFN get data, Data parsing: JSON Introduction

Source: Internet
Author: User

AFN: The data returned by the server can be automatically resolved by default, and the data returned by the server is parsed as JSON data.

It is a powerful class library which integrates XML parsing, JSON parsing, network image downloading, plist parsing, data flow request operation, uploading, downloading, caching and many other network functions.

Network access to data has always been the most important of mobile phone software, if the processing is not good, will result in a poor user experience. With the asihttprequest stop updating, the replacement network library is the inevitable thing, afnetworking is a good substitute. And all are lightweight, don't worry about joining too many libraries will have an impact on multi-software performance.

AFN precautions to use:

(1) a different parser must be selected in accordance with the data format returned by the server. Otherwise, you will get an error and you won't be getting the data you want.

(2) the data returned by the server must correspond to the Responseserializer. The corresponding relationship is as follows:

The 1> server is returning JSON data

* Afjsonresponseserializer

* Afhttpresponseserializer

The 2> server returns the XML data

* Afxmlparserresponseserializer

* Afhttpresponseserializer

3> The server is returning additional data

* Afhttpresponseserializer

How to use AFN and use scenarios:

The first thing you need to do is download the afnetworking library file, and when you download it you have to figure out what the minimum version of the software you are going to develop is. Afnetworking 2.0 or later versions require a xcode5.0 version and can only be run on a mobile system that is IOS6 or higher, and if you develop a Mac program, then version 2.0 will only run on Mac OS X 10.8 or higher

1. Create a network request manager

Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager];

2.

(1) By default, the parser for the network request Manager is as follows:

Because the JSON data is returned, the data returned from the server: the type of responseobject is Nsdictionary or Nsarray

Mgr.responseserializer = [Afjsonresponseserializer serializer];

(2)-If the server returns XML data, you must set the parser type for the network request manager as follows:

At this point, the data type returned by the server Responseobject is Nsxmlparser

Mgr.responseserializer = [Afxmlparserresponseserializer serializer];

(3) If the server is returning data (for example: file), you need to tell AFN not to parse the data returned by the server, keep the original data

Mgr.responseserializer = [Afhttpresponseserializer serializer];

1.2 ways to get JSON data through a URL

The first, using afjsonrequestoperation, the example given on the official website:

NSString *str=[nsstring stringwithformat:@ "Https://alpha-api.app.net/stream/0/posts/stream/global"];

Nsurl *url = [Nsurl urlwithstring:[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

Get JSON data from a URL

Afjsonrequestoperation *operation1 = [afjsonrequestoperation jsonrequestoperationwithrequest:request success:^ ( Nsurlrequest *request, Nshttpurlresponse *response, nsdictionary* JSON) {

NSLog (@ "The data obtained is:%@", JSON);

} failure:^ (Nsurlrequest *request, Nshttpurlresponse *response, nserror *error, id data) {

NSLog (@ "error occurred!) %@ ", error);

}];

[Operation1 start];

The second method, using Afhttprequestoperation to obtain the data in the form of a string, and then converted to JSON format, the nsstring format of the data into JSON data, using the IOS5 of the JSON parsing method:

NSString *str=[nsstring stringwithformat:@ "Https://alpha-api.app.net/stream/0/posts/stream/global"];

Nsurl *url = [Nsurl urlwithstring:[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

Afhttprequestoperation *operation = [[Afhttprequestoperation alloc] initwithrequest:request];

[Operation setcompletionblockwithsuccess:^ (afhttprequestoperation *operation, id responseobject) {

NSString *html = operation.responsestring;

nsdata* data=[html datausingencoding:nsutf8stringencoding];

ID dict=[nsjsonserialization jsonobjectwithdata:data options:0 error:nil];

NSLog (@ "The data obtained are:%@", dict);

}failure:^ (afhttprequestoperation *operation, Nserror *error) {

NSLog (@ "error occurred!) %@ ", error);

}];

Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];

[Queue addoperation:operation];

2. Get pictures by URL:

Asynchronously obtains a picture, is implemented through a queue, and the picture is cached, and the next time the same link is requested, the system automatically calls the cache without requesting data from the Web.

Uiimageview *imageview = [[Uiimageview alloc] Initwithframe:cgrectmake (0.0f, 100.0f, 100.0f, 100.0f)];

[ImageView setimagewithurl:[nsurl urlwithstring:@ "http://i.imgur.com/r4uwx.jpg"] placeholderimage:[uiimage imagenamed:@ "Placeholder-avatar"];

[Self.view Addsubview:imageview];

The method above is officially provided, and there is a way to

Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://www.scott-sherwood.com/ Wp-content/uploads/2013/01/scene.png "];

Afimagerequestoperation *operation = [Afimagerequestoperation imagerequestoperationwithrequest:request Imageprocessingblock:nil success:^ (nsurlrequest *request, Nshttpurlresponse *response, UIImage *image) {

Self.backgroundImageView.image = image;

} failure:^ (Nsurlrequest *request, Nshttpurlresponse *response, Nserror *error) {

NSLog (@ "Error%@", error);

}];

[Operation start];

If you use the first type of urlwithstring:placeholderimage: There will be more detail processing, in fact, or through afimagerequestoperation processing, you can click URLWithString: Placeholderimage: The method goes in to look at a glance. So the first kind of good.

3. How to get an XML file from a URL:

XML parsing uses afxmlrequestoperation, need to implement Apple's own Nsxmlparserdelegate delegate method, there are some unnecessary protocol format content in XML, so it can not be parsed like JSON, but also to implement the delegate. I've thought about it. Can all the XML links with a class processing, and with the server to do the communication, the results are very inconvenient, the effect is not good. Most XML tags are different, the format is not fixed, so there is a problem, the use of JSON is more convenient.

First step; Add the delegate nsxmlparserdelegate to the. h file

Step Two: Add code to the. m file method

Nsurl *url = [Nsurl urlwithstring:@ "Http://113.106.90.22:5244/sshopinfo"];

Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

Afxmlrequestoperation *operation =

[Afxmlrequestoperation xmlparserrequestoperationwithrequest:request success:^ (nsurlrequest *request, Nshttpurlresponse *response, Nsxmlparser *xmlparser) {

Xmlparser.delegate = self;

[Xmlparser Setshouldprocessnamespaces:yes];

[Xmlparser parse];

}failure:^ (nsurlrequest *request, Nshttpurlresponse *response, Nserror *error, Nsxmlparser *XMLParser) {

NSLog (@ "%@", error);

}];

[Operation start];

Step three; Implement a delegate method in a. m file

Triggered at the beginning of the document

-(void) Parserdidstartdocument: (Nsxmlparser *) parser{

NSLog (@ "parsing begins! ");

}

Parse start tag

-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary *) attributedict{

NSLog (@ "Mark:%@", elementname);

}

Parsing text nodes

-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string{

NSLog (@ "Value:%@", string);

}

Parse end tag

-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qname{

NSLog (@ "End tag:%@", elementname);

}

Trigger at end of document

-(void) Parserdidenddocument: (Nsxmlparser *) parser{

NSLog (@ "parsing is over! ");

}

4. How to use Afhttpclient for Web service operations

Afhttpclient handles get and post requests. Friends who make Web pages this method is used more. You can encapsulate and conserve resources when you want to call a request frequently.

baseurlstring = @ "http://www.raywenderlich.com/downloads/weather_sample/";

Nsurl *baseurl = [Nsurl urlwithstring:[nsstring stringwithformat:baseurlstring];

Nsdictionary *parameters = [nsdictionary dictionarywithobject:@ "JSON" forkey:@ "format"];

Afhttpclient *client = [[Afhttpclient alloc] initwithbaseurl:baseurl];

[Client Registerhttpoperationclass:[afjsonrequestoperation class]];

[Client setdefaultheader:@ "Accept" value:@ "text/html"];

[Client postpath:@ "weather.php" Parameters:parameters success:^ (afhttprequestoperation *operation, id responseObject ) {

nsstring* newstr = [[NSString alloc] Initwithdata:responseobject encoding:nsutf8stringencoding];

NSLog (@ "POST request:%@", NEWSTR);

}failure:^ (afhttprequestoperation *operation, Nserror *error) {

NSLog (@ "%@", error);

}];

[Client getpath:@ "weather.php" Parameters:parameters success:^ (afhttprequestoperation *operation, id responseObject) {

nsstring* newstr = [[NSString alloc] Initwithdata:responseobject encoding:nsutf8stringencoding];

NSLog (@ "GET Request:%@", NEWSTR);

}failure:^ (afhttprequestoperation *operation, Nserror *error) {

NSLog (@ "%@", error);

}];

Features of AFN:

    1. It has been updated and maintained, and is currently used by many people.
    2. Or a lot of users, then his information, documents, demo on more, very easy to find problems to solve.

afnetworking, Mknetworkkit and asihttprequest comparison:

According to the above comparison, afnetworking although compared to the Mknetworkkit function is weaker, but it is more extensible, and more maintenance, in the long run better than Mknetworkkit.

AFN get data, Data parsing: JSON introduction

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.