First, the simple and practical nsurlconnection
(i). Simple request Process
///1. Create a URL (resource path)Nsurl*url = [Nsurl urlwithstring:@"http://f.hiphotos.baidu.com/image/pic/item/d6ca7bcb0a46f21ff3649fbaf5246b600d33ae83.jpg"]; ///2. Create a requestnsurlrequest*request =[Nsurlrequest Requestwithurl:url]; ///3. Sending the request //3.1 Synchronization RequestsNSData *data =[nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil]; /*Data Processing*/ //3.2 Asynchronous Requests//an asynchronous request requires a request operation to be placed in an operations queueNsoperationqueue *queue =[[Nsoperationqueue alloc] init]; [Nsurlconnection sendasynchronousrequest:request Queue:queue Completionhandler:^ (Nsurlresponse * _nullable response, NSData * _nullable data, Nserror *_nullable Connectionerror) {
/*response,data,connectionerror Processing*/
}];
Code description
1. The home column can be obtained through the following code (the corresponding request is in the main thread, even if the nsurlconnection sends an asynchronous request).
Nsoperationqueue *queue = [Nsoperationqueue mainqueue];//get the home row
2. (3.1,3.2) Two methods are now discarded by Apple, replaced by the Nsurlsession method, Nsurlsession can be said to be nsurlconnection alternatives.
(ii). Data parsing (json/xml)
JSON parsing (nsjsonserialization)
// The nsjsonserialization class to convert JSON to Foundation objects // and convert Foundation objects to JSON. (API) // In short, we use the Nsjsonserialization class to convert between JSON and OC objects in the following way: // 1.json serialized into OC object Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil] ; // 2.oc object to JSON (not commonly used) [Nsjsonserialization datawithjsonobject:object options:nsjsonwritingprettyprinted Error:nil];
Code description
1. The data (JSON data) obtained through the network request is a binary stream, and we need to convert it to an OC object for operation.
XML parsing (nsxmlparser)
<?XML version= "1.0" encoding= "UTF-8"?>//File declaration (UTF-8 encoding)<Students>//students, student, name, age all indicate: element (or node)<Student> // <name>Ben</name>//Ben, M, 10 means: element properties<Sex>M</Sex> < Age>10</ Age> </Student> <Student> <name>Amy</name> <Sex>F</Sex> < Age>9</ Age> </Student> </Students>
Code description
1. This is a simple XML code that contains three basic components of XML (declarations, nodes, attributes)
{
// 1. Create an XML parser (data is the one that needs to be parsed) Nsxmlparser *xmlparser = [[Nsxmlparser alloc] initwithdata:data]; // 2. Setting up the agent Xmlparser. delegate = self ; // 3. Start parsing [Xmlparser parse];
// 4. Parse complete, refresh UI
/* Refresh UI */;
// de-parsing (Implementing parser:parseerroroccurred: Method)
[Xmlparser abortparsing];
}
#pragmaMark-nsxmlparser delegate///Sent by the parser object to the delegate when it begins parsing a document.///called when parsing begins- (void) Parserdidstartdocument: (Nsxmlparser *) parser{NSLog (@"parsing begins!");}///Start parse Element (node) City call- (void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname
NamespaceURI: (NSString *) NamespaceURI
QualifiedName: (NSString *) qName
Attributes: (nsdictionary<nsstring *,nsstring *> *) attributedict{//parse the required elements if([ElementName isequaltostring:@"Student"]) { //attributedict:contains any attributes associated with the element. //Keys is the names of attributes, and values are attribute values//extracting attributes of an elementNsdictionary *dict =attributedict; /*Other operations for data dictionary dict here*/} NSLog (@"");}///called when completed parsing- (void) Parserdidenddocument: (Nsxmlparser *) parser{NSLog (@"Parse complete!");}///called when an error occurs- (void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror{NSLog (@"Parse Error!");}
(iii). Post and get
//URLNsurl *url = [[Nsurl alloc] initwithstring:@"http://f.hiphotos.baidu.com/****"]; //Request//the request created by Nsurlrequest is a GET request. //the request created by Nsmutableurlrequest is also a GET request by default .//need to call HttpMethod to modify request modensurlrequest*request_get =[Nsurlrequest Requestwithurl:url]; //1. Create a requestNsmutableurlrequest *request_post =[Nsmutableurlrequest Requestwithurl:url]; //2. Set the request method to postRequest_post. HttpMethod =@"POST"; //3. Set the request body//httpbody is nsdata type, param string requires transcodingNSString *bodyparam = [NSString stringWithFormat:@"tel=%@&pwd=%@", tel, pwd]; Request_post. Httpbody=[Bodyparam Datausingencoding:bodyparam]; /*Send Request*/
Code description
1. You need to create a POST request to nsmutableurlrequest this class and need to set its httpmethod to @ "POST".
Second, the simple and practical nsurlsession
Comparison between Nsurlsession and Nsurlconnection
* Nsurlsession instance is a single case
* Nsurlsession send requests directly with URL, no additional request creation required
* Nsurlsession need to create tasks (Task)
* Nsurlsession send request need to open task
/*****General Request *****/ //Create sessionNsurlsession *session =[Nsurlsession sharedsession]; //Create a task from NsurlNsurlsessiondatatask *task =[session datataskwithurl:url completionhandler:^ (NSData * _Nullable data, NSURLResponse * _ Nullable Response, Nserror *_nullable Error) { /*data, response, error handling*/ }]; //Create a task from Nsurlrequest ( task /*Nsurlsessiondatatask *task = [Session Datataskwithrequest:request_get completionhandler:^ (NSData * _Nullable data , Nsurlresponse * _nullable response, Nserror * _nullable error) {}]; */ //Task Open[Task resume]; //Task paused[Task suspend];
/** * * * Download File Request * * **/ //Create sessionNsurlsession *session =[Nsurlsession sharedsession]; //Create a task with NsurlNsurlsessiondownloadtask *task =[session downloadtaskwithurl:url completionhandler:^ (NSURL * _Nullable location, Nsurlresponse * _nullable response, Nserror *_nullable Error) { /*data, response, error handling*/ }]; //Task Open[Task resume]; //Task paused[Task suspend];
Conclusion:
Today a little introduction to the use of nsurlconnection and nsurlsession, for network requests This is just the beginning, follow-up will introduce Nsurlconnection and Nsurlconnection proxy method of use, and will be accompanied by some demo.
Easy and practical iOS development-nsurlconnection and Nsurlsession