Use of iOS Development network data----afnetworking

Source: Internet
Author: User
Tags http authentication response code

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. 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./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;

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.

Error = Error Domain=com.alamofire.error.serialization.response code=-1016 "Request failed:unacceptable content-type: Text/html "Userinfo=0x1740f2c00 {com.alamofire.serialization.response.error.response= {url:http://192.168.5.132/ Api/cats?type=apps} {Status code:200, headers {

Connection = "Keep-alive";

"Content-type" = "text/html; Charset=utf-8 ";

Date = "Thu, 10:27:42 GMT";

Server = Nginx;

"Transfer-encoding" = Identity;

} }

AF can accept data other than JSON in its own arbitrary format can be used only to use the parsing method provided by Afnetwork, it only to the common format to do the data you return is not that format, he can't parse it out, you have to deal with the change Afne Twork's library file find the function that he's judging the wrong way to get him back from the correct method if you don't, just return to the wrong method of processing also can anyway the data has been to the network for the purpose of getting the data your data is just AFN Etwork that your data does not conform to the usual format does not match because your data is encrypted and is encrypted over the entire JSON format instead of just the value encryption so the transfer of this format can only modify the Afnetwork library and you won't Just use it first.

For example, what you're doing now is encrypting the entire string if you don't. Only partially encrypt the value and not encrypt the key is {"message": "Ciphertext of Value"} then this data still conforms to JSON format Afnetwork still can parse out You're encrypting the entire JSON string, and that cipher is not in JSON format, so you can do what I say. Only the encrypted Values section also handles the data in the wrong way in the current method, but you know that the data is correct, but afnetwork It's a mistake. This belongs to the principle of things can not be changed or not let afnetwork analysis he only through your own analysis if you let him help you to resolve you have to specify a format for him to specify a format and your data does not conform to the format that is returned by the wrong method

Afnetworking Questions about HTTP Authentication

Afnetwork The Basic authentication method is simple

Http://stackoverflow.com/questions/12440059/using-afnetworking-and-http-basic-authentication

Afnetwork Implementation of Digest certification

Creates a Nsurlcredential object and assigns the object to the request

https://github.com/AFNetworking/AFNetworking/issues/551 http://stackoverflow.com/questions/31784319/ Digest-access-authentication-for-afnetworking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:@"Username" password:@"Password" persistence:NSURLCredentialPersistenceForSession]; [manager setCredential:credential]; 

Use of iOS Development network data----afnetworking

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.