afnetworking use of iOS development network data

Source: Internet
Author: User
<span id="Label3"></p>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.<span><span>with the ASIHTTPRequest stop updating, it is necessary to replace the network library,</span></span>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.<strong><strong><span style="color: #ff0000;">How to select the Afnetworking version</span></strong></strong><p><p><span>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.</span></p></p>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,<span><span>need to use the latest released 0.10.x version</span></span><span><span>afnetworking 0.10.x</span></span>https://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;<span><span>currently the best choice is the 1.x version, compatible to IOS5.0. </span></span><strong><strong><span style="color: #ff0000;">How to get JSON data from a URL</span></strong></strong><span style="color: #333333;"><span style="color: #333333;">first, the Use</span> of</span>afjsonrequestoperation, An example given on the official website:<p><p>NSString *str=[nsstring stringwithformat:@ "https://alpha-api.app.net/stream/0/posts/stream/global"];</p></p><p><p>Nsurl *url = [nsurl urlwithstring:[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];</p></p><p><p>Nsurlrequest *request = [nsurlrequest requestwithurl:url];</p></p><p><p>Get JSON data from a URL</p></p><p><p>Afjsonrequestoperation *operation1 = [afjsonrequestoperation jsonrequestoperationwithrequest:requestsuccess:^ ( Nsurlrequest *request, nshttpurlresponse *response, nsdictionary* JSON) {</p></p><p><p>NSLog (@ "the data obtained is:%@", JSON);</p></p><p><p>} failure:^ (nsurlrequest *request, nshttpurlresponse *response, nserror *error, ID data) {</p></p><p><p>NSLog (@ "error occurred!) %@ ", error);</p></p><p><p>}];</p></p><p><p>[operation1 start];</p></p><p><p></p></p><p><p>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:</p></p><p><p>NSString *str=[nsstring stringwithformat:@ "https://alpha-api.app.net/stream/0/posts/stream/global"];</p></p><p><p>Nsurl *url = [nsurl urlwithstring:[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];</p></p><p><p>Nsurlrequest *request = [nsurlrequest requestwithurl:url];</p></p><p><p>Afhttprequestoperation *operation = [[afhttprequestoperation alloc] initwithrequest:request];</p></p><p><p>[operation setcompletionblockwithsuccess:^ (afhttprequestoperation *operation, ID Responseobject) {</p></p><p><p>NSString *html = operation.responsestring;</p></p><p><p>nsdata* data=[html datausingencoding:nsutf8stringencoding];</p></p><p><p>ID dict=[nsjsonserialization jsonobjectwithdata:data options:0 error:nil];</p></p><p><p>NSLog (@ "the data obtained are:%@", dict);</p></p><p><p>}failure:^ (afhttprequestoperation *operation, nserror *error) {</p></p><p><p>NSLog (@ "error occurred!) %@ ", error);</p></p><p><p>}];</p></p><p><p>Nsoperationqueue *queue = [[nsoperationqueue alloc] init];</p></p><p><p>[queue addoperation:operation];</p></p><p><p></p></p><p><p></p></p><p><p>If <strong>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</strong> stringbyaddingpercentescapesusingencoding:nsutf8stringencoding</p></p><p><p></p></p><p><p></p></p><p><p><strong><span style="color: #ff0000;">How to get a picture from a URL</span></strong></p></p><p><p>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.</p></p><pre><pre><br>Uiimageview *imageview = [[uiimageview alloc] initwithframe:cgrectmake (0.0f, 100.0f, 100.0f, 100.0f)];<br>[imageView Setimagewithurl:[nsurl urlwithstring:@ "http://i.imgur.com/r4uwx.jpg"]placeholderimage:[uiimage imagenamed:@ "placeholder-avatar"];<br>[self.view addsubview:imageview];</pre></pre><p><p>The method above is officially provided, and there is a way to</p></p><p><p>Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://www.scott-sherwood.com/ Wp-content/uploads/2013/01/scene.png "];</p></p><p><p>Afimagerequestoperation *operation = [afimagerequestoperation imagerequestoperationwithrequest: Requestimageprocessingblock:nil success:^ (nsurlrequest *request, nshttpurlresponse *response, UIImage *image) {</p></p><p><p>Self.backgroundImageView.image = image;</p></p><p><p>} failure:^ (nsurlrequest *request, nshttpurlresponse *response, nserror *error) {</p></p><p><p>NSLog (@ "error%@", error);</p></p><p><p>}];</p></p><p><p></p></p><p><p>[operation start];</p></p><p><p></p></p><p><p>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.</p></p><p><p></p></p><p><p><strong><span style="color: #ff0000;">How to get a plist file from a URL</span></strong></p></p><p><p>The content of the plist file is obtained by URL and is seldom used, and this method is not available in the official Method.</p></p><p><p>NSString *weatherurl = @ "http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";</p></p><p><p>Nsurl *url = [nsurl Urlwithstring:[weatherurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];</p></p><p><p>Nsurlrequest *request = [nsurlrequest requestwithurl:url];</p></p><p><p>[afpropertylistrequestoperation Addacceptablecontenttypes:[nsset setwithobject:@ "text/plain"];</p></p><p><p>Afpropertylistrequestoperation *operation = [afpropertylistrequestoperation Propertylistrequestoperationwithrequest:request success:^ (nsurlrequest *request, NSHTTPURLResponse *response, ID Propertylist) {</p></p><p><p>NSLog (@ "%@", (nsdictionary *) propertylist);</p></p><p><p></p></p><p><p>}failure:^ (nsurlrequest *request, nshttpurlresponse *response, nserror *error, ID propertylist) {</p></p><p><p>NSLog (@ "%@", error);</p></p><p><p>}];</p></p><p><p></p></p><p><p>[operation start];</p></p><p><p>If you're not careful, you might get <span> <strong>the error domain=afnetworkingerrordomain code=-1016 "expected content Type {(</strong></span></p></p><p><p><span><strong>"application/x-plist"</strong></span></p></p><p><p><span><strong>)}, got Text/plain "userinfo=0x16e91ce0 {nslocalizedrecoverysuggestion=</strong></span></p></p><p><p></p></p><p><p><span><strong>...</strong></span></p></p><p><p><span><strong>...</strong></span></p></p><p><p><span><strong>, afnetworkingoperationfailingurlrequesterrorkey= {}, nserrorfailingurlkey=, nslocalizeddescription=expected Content Type {(</strong></span></p></p><p><p><span><strong>"application/x-plist"</strong></span></p></p><p><p><span><strong>)}, got text/plain, afnetworkingoperationfailinponseerrorkey= {URL:} {status code:200, Headers {</strong></span></p></p><p><p><span><strong>"accept-ranges" = bytes;</strong></span></p></p><p><p><span><strong>Connection = "keep-alive";</strong></span></p></p><p><p><span><strong>"content-length" = 974;</strong></span></p></p><p><p><span><strong>"content-type" = "text/plain";</strong></span></p></p><p><p><span><strong>Date = "Sat, Jan 07:29:26 GMT";</strong></span></p></p><p><p><span><strong>Etag = "1014c2-3ce-4ee63e1c80e00" ";</strong></span></p></p><p><p><span><strong>"last-modified" = "Wed, Dec 23:04:24 GMT";</strong></span></p></p><p><p><span><strong>Server = "nginx/1.4.2";</strong></span></p></p><p><p></p></p><p><p><span><strong>} }}</strong></span></p></p><p><p>May also appear garbled, the solution is [afpropertylistrequestoperation addacceptablecontenttypes:[nsset setwithobject:@ "text/plain"];</p></p><p><p></p></p><p><p></p></p><p><p><strong><span style="color: #ff0000;">How to get XML data from a URL</span></strong></p></p><p><p><span style="color: #333333;">XML parsing uses</span> 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.</p></p><p><p>First step; Add the delegate nsxmlparserdelegate to The. h file</p></p><p><p>Step two: Add code to the. m file method</p></p><p><p>Nsurl *url = [nsurl urlwithstring:@ "http://113.106.90.22:5244/sshopinfo"];</p></p><p><p>Nsurlrequest *request = [nsurlrequest requestwithurl:url];</p></p><p><p>Afxmlrequestoperation *operation =</p></p><p><p>[afxmlrequestoperation xmlparserrequestoperationwithrequest:request success:^ (nsurlrequest *request, Nshttpurlresponse *response, nsxmlparser *xmlparser) {</p></p><p><p>Xmlparser.delegate = self;</p></p><p><p>[xmlparser setshouldprocessnamespaces:yes];</p></p><p><p>[xmlparser parse];</p></p><p><p>}failure:^ (nsurlrequest *request, nshttpurlresponse *response, nserror *error, nsxmlparser *XMLParser) {</p></p><p><p>NSLog (@ "%@", error);</p></p><p><p>}];</p></p><p><p>[operation start];</p></p><p><p>Step three; implement a delegate method in A. M file</p></p><p><p>Triggered at the beginning of the document</p></p><p><p>-(void) parserdidstartdocument: (nsxmlparser *) parser{</p></p><p><p>NSLog (@ "parsing begins! ");</p></p><p><p>}</p></p><p><p>Parse start tag</p></p><p><p>-(void) parser: (nsxmlparser *) parser didstartelement: (nsstring *) elementname namespaceuri: (nsstring *) NamespaceURI Qualifiedname: (nsstring *) qName attributes: (nsdictionary *) attributedict{</p></p><p><p>NSLog (@ "mark:%@", elementname);</p></p><p><p></p></p><p><p>}</p></p><p><p>Parsing text nodes</p></p><p><p>-(void) parser: (nsxmlparser *) parser foundcharacters: (nsstring *) string{</p></p><p><p>NSLog (@ "value:%@", string);</p></p><p><p>}</p></p><p><p>Parse end tag</p></p><p><p>-(void) parser: (nsxmlparser *) parser didendelement: (nsstring *) elementname namespaceuri: (nsstring *) NamespaceURI Qualifiedname: (nsstring *) qname{</p></p><p><p>NSLog (@ "end tag:%@", elementname);</p></p><p><p>}</p></p><p><p>Trigger at end of document</p></p><p><p>-(void) parserdidenddocument: (nsxmlparser *) parser{</p></p><p><p>NSLog (@ "parsing is over! ");</p></p><p><p>}</p></p><p><p>Results of the Operation:</p></p><br><strong><strong><span style="color: #ff0000;">How to use Afhttpclient for Web service operations</span></strong></strong><span><span>afhttpclient processing get and POST requests</span></span>This method is used more by friends who make Web Pages. You can encapsulate and conserve resources when you want to call a request frequently.<p><p>baseurlstring = @ "http://www.raywenderlich.com/downloads/weather_sample/";</p></p><p><p>Nsurl *baseurl = [nsurl urlwithstring:[nsstring stringwithformat:baseurlstring];</p></p><p><p>Nsdictionary *parameters = [nsdictionary dictionarywithobject:@ "json" forkey:@ "format"];</p></p><p><p>Afhttpclient *client = [[afhttpclient alloc] initwithbaseurl:baseurl];</p></p><p><p></p></p><p><p>[client registerhttpoperationclass:[afjsonrequestoperation class]];</p></p><p><p>[client setdefaultheader:@ "Accept" value:@ "text/html"];</p></p><p><p>[client postpath:@ "weather.php" parameters:parameters success:^ (afhttprequestoperation *operation, idresponseObject ) {</p></p><p><p>nsstring* newstr = [[nsstring alloc] initwithdata:responseobject encoding:nsutf8stringencoding];</p></p><p><p>NSLog (@ "post request:%@", newstr);</p></p><p><p>}failure:^ (afhttprequestoperation *operation, nserror *error) {</p></p><p><p>NSLog (@ "%@", error);</p></p><p><p>}];</p></p><p><p></p></p><p><p>[client getpath:@ "weather.php" parameters:parameters success:^ (afhttprequestoperation *operation, IdresponseObject) {</p></p><p><p>nsstring* newstr = [[nsstring alloc] initwithdata:responseobject encoding:nsutf8stringencoding];</p></p><p><p>NSLog (@ "get request:%@", newstr);</p></p><p><p>}failure:^ (afhttprequestoperation *operation, nserror *error) {</p></p><p><p>NSLog (@ "%@", error);</p></p><p><p>}];</p></p><p><p></p></p><p><p>Operation Result:</p></p>If you need to display the network activity indicator, you can use the following method: [afnetworkactivityindicatormanager sharedmanager].enabled = YES;<p><p></p></p><p><p><strong>error:error domain=afnetworkingerrordomain code=-1016 "Request failed:unacceptable content-type:text/html" Userinfo=0x16774de0 {nserrorfailingurlkey=http://</strong><strong>192.168.2.2</strong><strong>: 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 {</strong></p></p><p><p><strong>Xxx</strong></p></p><p><p></p></p><p><p><strong>}}, nslocalizeddescription=request failed:unacceptable content-type:text/html}</strong></p></p><p><p>The returned data is not in the correct format. Unregister this sentence: Op.responseserializer = [afjsonresponseserializer serializer]; Then convert the returned data yourself.</p></p><p><p>afnetworking use of iOS development network data</p></p></span>

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.