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, it is necessary to replace the network library,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. 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.
Afnetworking 2.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 afnetworking 1.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 versionafnetworking 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 software is estimated to be compatible with the minimum version will be 5.0 or even 6.0;currently the best choice is the 1.x version, compatible to IOS5.0.
How to get JSON data from a URLfirst, the use ofAfjsonrequestoperation, an 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:requestsuccess:^ ( 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];
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:[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 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 = @ "Http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";
Nsurl *url = [Nsurl urlwithstring:[weatherurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
[Afpropertylistrequestoperation addacceptablecontenttypes:[nsset setwithobject:@ "Text/plain"];
Afpropertylistrequestoperation *operation = [afpropertylistrequestoperation Propertylistrequestoperationwithrequest:request success:^ (nsurlrequest *request, NSHTTPURLResponse *response, ID PropertyList) {
NSLog (@ "%@", (Nsdictionary *) propertylist);
}failure:^ (nsurlrequest *request, Nshttpurlresponse *response, nserror *error, id propertylist) {
NSLog (@ "%@", error);
}];
[Operation start];
If you're not careful, you might get the error domain=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:26 GMT";
Etag = "1014c2-3ce-4ee63e1c80e00" ";
"Last-modified" = "Wed, Dec 23:04:24 GMT";
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, we need to implement Apple's own Nsxmlparserdelegate delegate method, XML has some unnecessary protocol format content, so you can not parse 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! ");
}
Results of the operation:
How to use Afhttpclient for Web service operationsafhttpclient processing get and POST requestsThis method is used more by friends who make Web pages. 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, IdresponseObject) {
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;
Time is limited, first write to this, because there is no server, many features can not be tested, if some friends, want to borrow servers to test, mutual exchange: qq:915893620
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:unacceptable content-type:text/html}
The returned data is not in the correct format. Unregister this sentence: Op.responseserializer = [Afjsonresponseserializerserializer]; then convert the returned data to itself.
afnetworking use of iOS development network data