How to select the Afnetworking version
Official website Download version 2.5: http://afnetworking.com/
This article is based on AFNetworking2.0, if you are using version 2.5, see this article: AFNetworking2.5 use
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, if you develop a Mac program, then the 2.0 version is only available on mac OS X 10.8 or higher version to run.
Afnetworking 2.0 of 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 released 1.x version
Afnetworking 1.x of https://github.com/AFNetworking/AFNetworking/tree/1.x
If you are compatible with 4.3 or Mac OS X 10.6, you need to use the latest released 0.10.x version
Afnetworking 0.10.xhttps://github.com/AFNetworking/AFNetworking/tree/0.10.x
How to get JSON data from a URL
The first, using Afjsonrequestoperation, the example given on the official website:
[OBJC "View plaincopy on code to see a snippet derived from my Code slice 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 URL afjsonrequestoperation *operation1 = [Afjsonrequestoperation jsonrequestoperationwithrequest:reques T success:^ (nsurlrequest *request, Nshttpurlresponse *response, nsdictionary* JSON) {NSLog (@ "Gets the data:%@", 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 IOS5 's own 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, Idresponseobject) {NSString*html =operation.responsestring; NSData* Data=[HTML datausingencoding:nsutf8stringencoding]; IDDict=[nsjsonserialization jsonobjectwithdata:data Options:0Error:nil]; NSLog (@"the data obtained is:%@", Dict); }failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@"An error has 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 urlwithstring: placeholderimage: There will be more details, in fact, the implementation or through the Afimagerequestoperation processing, You can click URLWithString: Placeholderimage: the way to see it 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, idpropertylist) { NSLog (@ "%@", error ); }]; [Operation start];
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, You have 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); }//Parse text node-(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 (@ "Parse end!) "); The result of the run: How to use Afhttpclient for Web service operations [OBJC] View plaincopy on code to see that the snippet derives to my code slice afhttpclient handles get and Post request. 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:responseObjectencoding: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:responseObjectencoding:NSUTF8StringEncoding]; NSLog (@ "GET Request:%@", NEWSTR); }failure:^ (AFhttprequestoperation *operation, Nserror *error) {NSLog (@ "%@", error); }];
afnetworking use of iOS development network data