iOS Development Network Learning AFN Three: serialization of AFN

Source: Internet
Author: User

#import "ViewController.h"#import "AFNetworking.h"@interfaceViewcontroller () <NSXMLParserDelegate>@end@implementationViewcontroller-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event{[self httpData2];}//The JSON data is returned-(void) json{//1. Create a Session ManagerAfhttpsessionmanager *manager =[Afhttpsessionmanager Manager]; //http://120.25.226.186: 32812/login?username=123&pwd=122&type=json//nsdictionary*paramdict = @{                                @"username":@"520it",                                @"pwd":@"520it",                                @"type":@"JSON"                                }; //2. Send a GET request    /*first parameter: The request path (does not contain parameters). NSString Second parameter: Dictionary (data ~ parameter sent to server) third parameter: Progress progress callback Fourth parameter: Success successfully callback task: Request task Responseobject: Response Body Information ( JSON--->oc object) Response: Request header information Fifth parameter: Failure failure callback error: Error message response header: Task.response*/[Manager GET:@"Http://120.25.226.186:32812/login"Parameters:paramdict Progress:nil success:^ (nsurlsessiondatatask * _nonnull task,ID_nullable Responseobject) {NSLog (@"%@---%@", [Responseobjectclass],responseobject); } Failure:^ (Nsurlsessiondatatask * _nullable task, Nserror *_nonnull Error) {NSLog (@"request failed--%@", error); }];}//returned is the XML-(void) xml{//1. Create a Session ManagerAfhttpsessionmanager *manager =[Afhttpsessionmanager Manager]; //http://120.25.226.186: 32812/login?username=123&pwd=122&type=json//        //Note: If you are returning XML data, you should modify the parsing scheme of the AFNManager.responseserializer =[Afxmlparserresponseserializer Serializer]; Nsdictionary*paramdict = @{                                @"type":@"XML"                                }; //2. Send a GET request    /*first parameter: The request path (does not contain parameters). NSString Second parameter: Dictionary (data ~ parameter sent to server) third parameter: Progress progress callback Fourth parameter: Success successful callback task: Request task Responseobject: Response body information (JSON--->OC object) Fifth parameter: Failure failure callback error: Error message response header: Task.response*/[Manager GET:@"Http://120.25.226.186:32812/video"Parameters:paramdict Progress:nil success:^ (nsurlsessiondatatask * _nonnull Task,nsxmlparser *parser) {                //NSLog (@ "%@---%@", [Responseobject class],responseobject); //nsxmlparser *parser = (Nsxmlparser *) Responseobject; //Set up proxyParser.Delegate=Self ; //Start parsing[parser Parse]; } Failure:^ (Nsurlsessiondatatask * _nullable task, Nserror *_nonnull Error) {NSLog (@"request failed--%@", error); }];}//Binary data returned-(void) httpdata{//1. Create a Session ManagerAfhttpsessionmanager *manager =[Afhttpsessionmanager Manager]; /** Response body information By default, the JSON type is returned: AFN has three types, default Json,xml, and others, * 1: NOTE: If you are returning XML data, you should modify the parsing scheme of the AFN Afxmlparserresponseseria             Lizer,manager.responseserializer = [Afxmlparserresponseserializer serializer];     2: NOTE: If the returned data is neither XML nor JSON then the parsing scheme should be modified as: Manager.responseserializer = [Afhttpresponseserializer serializer]; */Manager.responseserializer=[Afhttpresponseserializer Serializer]; //2. Send a GET request[Manager GET:@"Http://120.25.226.186:32812/resources/images/minion_01.png"Parameters:nil Progress:nil success:^ (nsurlsessiondatatask * _nonnull task,ID_nullable Responseobject) {NSLog (@"%@-", [Responseobjectclass]); //UIImage *image = [UIImage imagewithdata:responseobject];} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror *_nonnull Error) {NSLog (@"request failed--%@", error); }];}/** * AFN unknown data type: Like what Text/html,text/plain, is not supported by AFN, so must be configured, preferably outside the configuration, do not modify the contents of the AFN internal framework. Two items need to be configured: 1: Tell AFN to accept text/html type of data, manager.responseSerializer.acceptableContentTypes = [Nsset setwithobject:@ "text/ HTML "]; 2: If not json,xml, other types must be configured with a low of three types: Manager.responseserializer = [Afhttpresponseserializer serializer]. both are indispensable*/-(void) httpdata2{//1. Create a Session ManagerAfhttpsessionmanager *manager =[Afhttpsessionmanager Manager]; //tell AFN to accept text/html types of dataManager.responseSerializer.acceptableContentTypes = [Nsset setwithobject:@"text/html"]; Manager.responseserializer=[Afhttpresponseserializer Serializer]; //2. Send a GET request[Manager GET:@"http://www.baidu.com"Parameters:nil Progress:nil success:^ (nsurlsessiondatatask * _nonnull task,ID_nullable Responseobject) {NSLog (@"%@-%@", [Responseobjectclass],[[nsstring Alloc]initwithdata:responseobject encoding:nsutf8stringencoding]); //UIImage *image = [UIImage imagewithdata:responseobject];} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror *_nonnull Error) {NSLog (@"request failed--%@", error); }];}#pragmaMark----------------------#pragmaMark Nsxmlparserdelegate-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary<nsstring *,nsstring *> *) attributedict{NSLog (@"%@--%@", elementname,attributedict);}@end

/*

1.AFN it internally by default the server response data as JSON to parse, so if the server returned to me is not JSON data then request an error, this time need to set the AFN response information parsing. AFN provides three ways to parse the response information, namely:

1) afxmlparserresponseserializer----XML

2) Afhttpresponseserializer---------default binary response data

3) Afjsonresponseserializer---------JSON

2. There is also a situation where the data format returned to us by the server is inconsistent (developer tool Content-type:text/xml), then it is possible that the request is unsuccessful. Workaround:

1) directly in the source code to modify, add the corresponding Content-type

2) Get this attribute and add it to the collection

3. Related code

-(void) Srializer

{

1. Create request manager, internal based on nsurlsession

Afhttpsessionmanager *manager = [Afhttpsessionmanager manager];

/* Knowledge point 1: Set AFN in what way to parse the data returned by the server */

If the XML is returned, tell AFN that the response is parsed using XML

Manager.responseserializer = [Afxmlparserresponseserializer serializer];

If the binary data is returned, the default binary is used to parse the data

Manager.responseserializer = [Afhttpresponseserializer serializer];

Use JSON to parse the data

Manager.responseserializer = [Afjsonresponseserializer serializer];

/* Knowledge point 2 tells AFN to support this type when serializing the data returned by the server

[Afjsonresponseserializer serializer].acceptablecontenttypes = [Nsset setwithobject:@ "Text/xml"];

2. To load all the request parameters in a dictionary, the Get method will automatically take all the key-value pairs out to the & symbol and finally use. Symbolic connection behind the request path

Nsdictionary *dict = @{

@ "username": @ "223",

@ "pwd": @ "EWR",

@ "type": @ "XML"

};

3. Send a GET request

[Manager get:@ "Http://120.25.226.186:32812/login" Parameters:dict success:^ (Nsurlsessiondatatask * _nonnull task, ID _ Nonnull responseobject) {

4. Request a successful callback block

NSLog (@ "%@", [Responseobject class]);

} failure:^ (Nsurlsessiondatatask * _nonnull task, Nserror * _nonnull error) {

5. Request failed callback, you can print error value to view fault information

NSLog (@ "%@", error);

}];

}

```

iOS Development Network Learning AFN Three: serialization of AFN

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.