afnetworking use of iOS development network data

Source: Internet
Author: User

HTTP network library is a powerful class library which integrates XML parsing, JSON parsing, network image downloading, plist parsing, data flow request operation, uploading, downloading, caching and so on. The latest version supports Session,xctool unit testing. 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. 1. Why use a third-party network library? First of all, if you do not use the network library, I once felt that everything with Apple native Good, XML parsing with Apple's own delegation, download the picture to write their own, if you have the same experience with me, then you will find that management is very complex, easy to make mistakes. And the performance is not good. If you are a pursuit of perfection, then put down your stubborn, as I did, try the network Library bar. 2. Why use afnetworking? 1th, it was updated and maintained, and the current user a lot of, 2nd, or a lot of users, then his information, documents, demo on more, very easy to find problems to solve. If not afnetworking, there is a kind of mknetworkkit is also good, may wish to try. How to select the Afnetworking version

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. AFNetworking2.0 or later versions require a xcode5.0 version and can only be run on a IOS6 or higher phone system, and if you develop a Mac program, the 2.0 version can only run on MacOS X 10.8 or higher.

AFNetworking2.0 https://github.com/AFNetworking/AFNetworking If you want to be compatible with IOS5 or Mac OS X 10.7, then you need to use the latest release of the 1.x version of afnetworking1.x https://github.com/AFNetworking/AFNetworking/tree/1.x if you want to be compatible with 4.3 or Mac OS X 10.6, need to use the latest released 0.10.x version afnetworking 0.10.xhttps://github.com/afnetworking/afnetworking/tree/0.10.x 2013 most software compatible minimum version is 4.3, and 2014, most of the estimated compatibility of the minimum version will be 5.0 or even 6.0, so the best choice is the 1.x version, compatible to IOS5.0. How to get JSON data via URL The first kind, 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:[strstringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

Nsurlrequest *request = [Nsurlrequestrequestwithurl:url];

Get JSON data from a URL

Afjsonrequestoperation *operation1 = [Afjsonrequestoperationjsonrequestoperationwithrequest: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 =[[afhttprequestoperationalloc] initwithrequest:request];

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

nsstring*html = operation.responsestring;

nsdata* data=[html datausingencoding:nsutf8stringencoding];

ID dict=[nsjsonserialization jsonobjectwithdata:dataoptions:0 Error:nil];

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

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

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

}];

Nsoperationqueue *queue = [[Nsoperationqueuealloc] init];

[Queue addoperation:operation];

If error domain=nsurlerrordomain code=-1000 "Bad url" userinfo=0x14defc80 {nsunderlyingerror=0x14deea10 ' bad URL ', Nslocalizeddescription=bad URL This error, please check the URL encoding format. Is there any stringbyaddingpercentescapesusingencoding:nsutf8stringencoding

How to get a picture from a 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:[nsurlurlwithstring:@ "http://www.scott-sherwood.com/ Wp-content/uploads/2013/01/scene.png "];

Afimagerequestoperation *operation = [Afimagerequestoperationimagerequestoperationwithrequest: requestimageprocessingblock:nilsuccess:^ (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 I think it's better to use the first kind.

How to get a plist file from a URL

The content of the plist file is obtained by URL and is seldom used, and this method is not available in the official method.

NSString *weatherurl [email protected] "http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";

Nsurl *url =[nsurl urlwithstring:[weatherurlstringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

Nsurlrequest *request = [Nsurlrequestrequestwithurl:url];

[Afpropertylistrequestoperationaddacceptablecontenttypes:[nsset setwithobject:@ "Text/plain"];

Afpropertylistrequestoperation*operation =[ afpropertylistrequestoperationpropertylistrequestoperationwithrequest:requestsuccess:^ (NSURLRequest *request, Nshttpurlresponse *response, id propertylist) {

NSLog (@ "%@", (Nsdictionary *) propertylist);

}failure:^ (nsurlrequest *request, Nshttpurlresponse *response, nserror *error, id propertylist) {

NSLog (@ "%@", error);

}];

[Operation start];

If you are not careful, you may appear errordomain=afnetworkingerrordomain code=-1016 "Expected content type{(

"Application/x-plist"

)}, got Text/plain "Userinfo=0x16e91ce0 {nslocalizedrecoverysuggestion=

...

...

, afnetworkingoperationfailingurlrequesterrorkey= {},nserrorfailingurlkey=, nslocalizeddescription=expected Content type{(

"Application/x-plist"

)}, got text/plain,afnetworkingoperationfailinponseerrorkey= {URL:} {status code:200, headers {

"Accept-ranges" = bytes;

Connection = "Keep-alive";

"Content-length" = 974;

"Content-type" = "Text/plain";

Date = "Sat, Jan 07:29:26gmt";

Etag = "1014c2-3ce-4ee63e1c80e00" ";

"Last-modified" = "Wed, Dec 23:04:24gmt";

Server = "nginx/1.4.2";

} }}

May also appear garbled, the solution is [afpropertylistrequestoperation addacceptablecontenttypes:[nsset setwithobject:@ "Text/plain"];

How to get XML data 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 = [nsurlurlwithstring:@ "Http://113.106.90.22:5244/sshopinfo"];

Nsurlrequest *request = [Nsurlrequestrequestwithurl:url];

Afxmlrequestoperation *operation =

[Afxmlrequestoperationxmlparserrequestoperationwithrequest:request success:^ (Nsurlrequest *request, Nshttpurlresponse *response,nsxmlparser *xmlparser) {

Xmlparser.delegate = self;

[Xmlparsersetshouldprocessnamespaces: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 *) Parserdidstartelement: (nsstring*) elementname NamespaceURI: (NSString *) Namespaceuriqualifiedname: (nsstring*) Qnameattributes: (nsdictionary*) attributedict{

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

}

Parsing text nodes

-(void) Parser: (Nsxmlparser *) Parserfoundcharacters: (nsstring*) string{

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

}

Parse end tag

-(void) Parser: (Nsxmlparser *) Parserdidendelement: (nsstring*) elementname NamespaceURI: (NSString *) Namespaceuriqualifiedname: (nsstring*) qname{

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

}

Trigger at end of document

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

NSLog (@ "parsing is over! ");

}

Results of the operation:


How to use Afhttpclient for Web service operations Afhttpclient handle 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 [email protected] "http://www.raywenderlich.com/downloads/weather_sample/";

Nsurl*baseurl = [nsurlurlwithstring:[nsstringstringwithformat:baseurlstring]];

Nsdictionary *parameters = [nsdictionarydictionarywithobject:@ "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);

}];

Operation Result:

If you need to display the network activity indicator, you can use the following method: [Afnetworkactivityindicatormanager sharedmanager].enabled =yes;

Error:error domain=afnetworkingerrordomain code=-1016 "Request failed:unacceptable content-type:text/html" UserInfo= 0x16774de0{nserrorfailingurlkey=http://192.168.2.2:8181/ecar/tsp/uploadlocation? cid=781666&servicetype=1,afnetworkingoperationfailinponseerrorkey= {url:http://192.168.2.2:8181/ecar/tsp/ Uploadlocation? cid=781666&servicetype=1} {Status code:200, headers {

Xxx

}}, Nslocalizeddescription=request failed:unacceptablecontent-type:text/html}

The returned data is not in the correct format. Unregister this sentence: op.responseserializer= [Afjsonresponseserializer Serializer]; then convert the returned data yourself.

From the original: http://blog.sina.com.cn/s/blog_68661bd80101r1xz.html

afnetworking use of iOS development network data

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.