iOS Learning notes-network programming

Source: Internet
Author: User

I. HTTP protocol
1. Interview questions: Talk about the HTTP protocol (express your view of the HTTP protocol)
* Full name of HTTP protocol: Hypertext Transfer Protocol, specification for custom transfer data (data transfer specification between client and server)
* Describe the HTTP protocol complete communication process

2. Communication process
1> Request
* Client-to-server
* Content of the request
A. " Request Line: Request method \ Request Resource Path \http protocol version
Get/mjserver/login?username=123&pwd=123&method=get&type=json http/1.1

B. " Request Header ": Client-side information
host:192.168.1.200:8080
User-agent:iphone Simulator; IPhone OS 7.1; en_US
Accept:text/html
accept-language:zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-encoding:gzip, deflate

C. " Request Body ": POST request only need to have, store specific data
* such as file data
* such as the parameter data of the POST request

2> response
* Server-to-client
* Content of the response
A. " Status line ": HTTP protocol version \ Status code \ Status information, also known as" response line "
http/1.1 OK

B. " Response Header ": Server information \ type of returned data \ length of returned data
server:apache-coyote/1.1
Content-type:application/json;charset=utf-8
content-length:248

C. " Entity content ": the specific content returned to the client, also known as the" response body "
* such as JSON data returned by the server
* such as file data returned by the server

3.HTTP method of Request
1> GET
* Parameters are stitched behind the URL
* Parameters are Limited

2> POST
* Parameters are in the request body
* No restrictions on parameters
* File upload can only be used post

3> head: Get response header information without getting the response body

The means of sending get\post requests in 4.iOS
1> nsurlconnection
* Apple native
* It's more complicated than Asi\afn.

2> ASI
* Based on Cfnetwork
* Provides a lot of powerful features, easy to use

3> AFN
* Based on Nsurlconnection
* Provides a common function, easy to use

4> recommendations
* In order to improve development efficiency and reduce the time spent debugging, try to use the famous simple third-party framework
* Therefore, to process HTTP requests, it is more recommended to use the ASI latter AFN

Two. nsurlconnection
1. Sending the request
1> Send a sync request
+ (NSData *) Sendsynchronousrequest: (nsurlrequest *) Request Returningresponse: (Nsurlresponse *) Response error: ( Nserror * *) error;

2> sending an asynchronous request (block)
+ (void) Sendasynchronousrequest: (nsurlrequest*) Request
Queue: (nsoperationqueue*) queue
Completionhandler: (void (^) (nsurlresponse* response, nsdata* data, nserror* connectionerror)) handler;

3> sending an asynchronous request (proxy method)
[Nsurlconnection connectionwithrequest:request delegate:self];
[[Nsurlconnection alloc] initwithrequest:request delegate:self];
[[Nsurlconnection alloc] initwithrequest:request delegate:self Startimmediately:yes];

Nsurlconnection *conn = [[Nsurlconnection alloc] initwithrequest:request delegate:self Startimmediately:no];
[Conn start];

2. File Download (large file download)
1> implementation scenario: Side Download Side writes (writes to a file in the sandbox)
2> Concrete Implementation Steps
A. When receiving a response from the server
Create an empty file-Nsfilemanager
[Mgr CreateFileAtPath:self.destPath Contents:nil Attributes:nil];

Creates a handle object associated with an empty file-Nsfilehandle
[Nsfilehandle FileHandleForWritingAtPath:self.destPath];

B. When receiving data from the server
Writes the data returned by the server to the end of the file using a handle object
Move to the end of a file
[Self.writehandle Seektoendoffile];
Writes data starting at the current moving position (end of file)
[Self.writehandle Writedata:data];

C. When the data returned by the server is received
Close handle
[Self.writehandle CloseFile];
Self.writehandle = nil;

3. Breakpoint Download
1> Key Technology points
* Set the request header range to tell the server which data to download

4. File Upload
1> Clear
* Can only be requested by post
* Request parameters are in the request body (file parameters \ non-file type of normal parameters)

2> implementation Steps
A. Stitching the request body (file parameters \ non-file type of normal parameters)
* File Parameters
Start tag of the parameter (split line)
--heima\r\n
Parameter description (parameter name ...)
Content-disposition:form-data; Name= "parameter name"; filename= "filename" \ r \ n
File type
Content-type: type of File mimetype\r\n
Binary data for files (parameter values)
\ r \ n
Binary data for files
\ r \ n

* Non-file parameters (normal parameters)
Start tag of the parameter (split line)
--heima\r\n
Parameter description (parameter name ...)
Content-disposition:form-data; Name= "parameter name" \ r \ n
Parameter values
\ r \ n
Parameter values
\ r \ n

* Mark end of all parameters
--heima--\r\n

B. Setting the request header
* Length of the request body
Content-length: Length of the request body (bytes length)

* Type of request data
Content-type:
Normal POST request: application/x-www-form-urlencoded
Post request to upload file: multipart/form-data; Boundary=--heima

5.JSON and XML
1>. JSON conversion to OC data type
In iOS, there are 4 common parsing scenarios for JSON
Third-party frameworks: Jsonkit, Sbjson, Touchjson (performance from left to right, worse)
Apple native (comes with): Nsjsonserialization (Best performance)
Common methods of Nsjsonserialization
OC object, JSON data
+ (ID) jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: (NSERROR *) error;
OC Object--JSON data
+ (NSData *) Datawithjsonobject: (ID) obj options: (nsjsonwritingoptions) opt error: (NSERROR *) error;
2>. Convert XML to OC data type
There are 2 ways to parse XML
DOM: Loading an entire XML document into memory at once, which is more suitable for parsing small files
SAX: Starting from the root element, in order to parse an element down, it is more suitable for parsing large files
Apple native
Nsxmlparser:sax method analysis, easy to use
Third-party frameworks
LIBXML2: pure C language, which is included by default in the iOS SDK while supporting DOM and sax parsing
Gdataxml:dom method Analysis, developed by Google, based on LIBXML2
A. Nsxmlparser
Incoming XML data, creating a parser
Nsxmlparser *parser = [[Nsxmlparser alloc] initwithdata:data];
Set up the agent to listen to the parsing process
Parser.delegate = self;
Start parsing
[Parser parse];
Nsxmlparserdelegate
Called when scanning to the beginning of a document (parsing is started)
-(void) Parserdidstartdocument: (Nsxmlparser *) parser
Called when scanning to the end of a document (parsing is complete)
-(void) Parserdidenddocument: (Nsxmlparser *) parser
Called when scanning to the beginning of an element (Attributedict holds the attributes of the element)
-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary *) attributedict
Called when scanning to the end of an element
-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qName

Three. Nsurlcache
Steps to use the cache
Get a global cache object
Nsurlcache *cache = [Nsurlcache Sharedurlcache];

Set Cache capacity
cache.memorycapacity = 1024 * 1024;
cache.diskcapacity = 20 * 1024 * 1024;

Set the requested cache policy
Request.cachepolicy = Nsurlrequestreturncachedataelseload;

Four. ASI
1. Steps to use the cache
1> Caching Individual requests
1. Get a global cache object (determines where the cache is stored and where to store it)
Asidownloadcache *cache = [Asidownloadcache Sharedcache];
Set the default cache load policy
Cache.defaultcachepolicy = Asidonotreadfromcachecachepolicy;

2. Set the cache object for the request object (which cache object to use)
Request.downloadcache = cache;

3. Set the cache load policy for the request object
Request.cachepolicy = Asionlyloadifnotcachedcachepolicy;
Send a request if there is no cache

4. Set the cache storage policy for the request object (length of storage)
Request.cachestoragepolicy = Asicachepermanentlycachestoragepolicy;
Permanent storage

Note the priority of the cache load policy: request.cachepolicy > Cache.defaultcachepolicy

2> Cache all requests
1. Get a global cache object (determines where the cache is stored and where to store it)
Asidownloadcache *cache = [Asidownloadcache Sharedcache];
Set the default cache load policy
Cache.defaultcachepolicy = Asionlyloadifnotcachedcachepolicy;

2. Setting the global Cache object
[ASIHTTPRequest Setdefaultcache:cache];

2. Sending the request
1> Sync Request
[Request startsynchronous];

2> Asynchronous requests
[Request startasynchronous];

3.get\post
1> GET Request
ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];

2> POST Request
Asiformdatarequest *request = [Asiformdatarequest Requestwithurl:url];
Add normal parameter (non-file parameter)
[Request setpostvalue:@ "Zhangsan" forkey:@ "username"];
[Request setpostvalue:@ "123" forkey:@ "pwd"];

4. File download
The path to where files are stored (where files are downloaded)
Request.downloaddestinationpath = filepath;
Set up Download agent (listen for download progress)
Request.downloadprogressdelegate = Self.circleview;
Support Breakpoint Download
Request.allowresumeforfiledownloads = YES;

5. File Upload
Add File parameter (file: path to upload files)
[Request Setfile:file forkey:@ "file"];
[Request Setfile:file withfilename:@ "123.txt" andcontenttype:@ "Text/plain" forkey:@ "file"];
[Request Setdata:data withfilename:@ "Minion.png" andcontenttype:@ "image/png" forkey:@ "file"];

Set up upload agent (listen for upload progress)
Request.uploadprogressdelegate = Self.circleview;

6. The process of listening for requests
1> Proxy method
Set up Proxy
Request.delegate = self;
Compliance Agreement
Asihttprequestdelegate
Implementing proxy methods in the Protocol
-(void) requeststarted: (asihttprequest *) request;
-(void) Request: (ASIHTTPRequest *) Request Didreceivedata: (NSData *) data
-(void) requestfinished: (asihttprequest *) request;
-(void) requestfailed: (asihttprequest *) request;

2> SEL
Set up Proxy
Request.delegate = self;
Set method Name
[Request Setdidstartselector: @selector (start)]; Starts sending the request, the proxy's Start method is invoked
// ....

3> Block
[Request setstartedblock:^{
NSLog (@ "setstartedblock----");
}];

[Request setdatareceivedblock:^ (NSData *data) {
NSLog (@ "setdatareceivedblock----");
}];

[Request setcompletionblock:^{
NSLog (@ "setcompletionblock----");
}];

[Self setfailedblock:^{
NSLog (@ "setfailedblock----");
}];

7. Get the server's response through the request object
1> Getting response header information
@property (Atomic, retain) Nsdictionary *responseheaders;

2> Get response Body (entity content)
-(NSData *) responsedata; Returns binary data directly to the server
-(NSString *) responsestring; Convert binary data to strings (easy debugging)

Five. AFN
1.get\post
1> GET Request
1. Obtaining the Request Manager
Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager];

2. Package Request Parameters
Nsmutabledictionary *params = [Nsmutabledictionary dictionary];
params[@ "username"] = @ "123";
params[@ "pwd"] = @ "123";

3. Send a GET request
[Mgr get:@ "Http://192.168.1.200:8080/MJServer/login" Parameters:params
success:^ (afhttprequestoperation *operation, id responseobject) {
NSLog (@ "Request successfully---%@", responseobject);
}
failure:^ (afhttprequestoperation *operation, Nserror *error) {
NSLog (@ "Request failed---%@", error);
}];


2> POST Request
1. Obtaining the Request Manager
Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager];

2. Package Request Parameters
Nsmutabledictionary *params = [Nsmutabledictionary dictionary];
params[@ "username"] = @ "123";
params[@ "pwd"] = @ "123";

3. Send a POST request
[Mgr post:@ "Http://192.168.1.200:8080/MJServer/login" Parameters:params
success:^ (afhttprequestoperation *operation, id responseobject) {
NSLog (@ "Request successfully---%@", responseobject);
}
failure:^ (afhttprequestoperation *operation, Nserror *error) {
NSLog (@ "Request failed---%@", error);
}];

2. File Upload
1. Obtaining the Request Manager
Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager];

2. Send the request (do file upload)
#warning parameters: Only non-file parameters can be placed
Nsmutabledictionary *params = [Nsmutabledictionary dictionary];
params[@ "username"] = @ "Zhangsan";

[Mgr post:@ "Http://192.168.1.200:8080/MJServer/upload" Parameters:params
constructingbodywithblock:^ (id<afmultipartformdata> formData) {
Be sure to add the file parameter to this block

Loading file data
NSString *file = [[NSBundle mainbundle] pathforresource:@ "test.txt" oftype:nil];
NSData *data = [NSData datawithcontentsoffile:file];

Stitching file Parameters
[FormData appendpartwithfiledata:data name:@ "file" filename:@ "123.txt" mimetype:@ "Text/plain"];
}
success:^ (afhttprequestoperation *operation, id responseobject) {
NSLog (@ "Upload successful----%@", responseobject);
} failure:^ (Afhttprequestoperation *operation, Nserror *error) {
NSLog (@ "Upload failed----%@", error);
}];

Six. Network Status monitoring
1.Reachability
Notification of monitoring network status changes
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (networkstatechange) Name: Kreachabilitychangednotification Object:nil];

Create reachability
Self.conn = [reachability reachabilityforinternetconnection];
Start monitoring the network (notify Kreachabilitychangednotification once the network status changes)
[Self.conn Startnotifier];

Handling Network status changes
-(void) Networkstatechange
{
1. Detect WiFi Status
reachability *wifi = [reachability Reachabilityforlocalwifi];

2. Check whether the mobile phone can be on the network (wifi\3g\2.5g)
reachability *conn = [reachability reachabilityforinternetconnection];

3. Determine network status
if ([WiFi currentreachabilitystatus]! = notreachable) {//WiFi available
NSLog (@ "WiFi");
} else if ([conn currentreachabilitystatus]! = notreachable) {//not using WiFi, use your phone to bring your own network to the Internet
NSLog (@ "Use your phone to bring your own network to the Internet");
} else {//no network
NSLog (@ "no network");
}
}

2.AFN
1. Managers who have access to network monitoring
Afnetworkreachabilitymanager *mgr = [Afnetworkreachabilitymanager Sharedmanager];

2. Set up the processing after the network status change
[Mgr setreachabilitystatuschangeblock:^ (afnetworkreachabilitystatus status) {
When the network state changes, the block is called
Switch (status) {
Case Afnetworkreachabilitystatusunknown://Unknown network
NSLog (@ "Unknown network");
Break

Case afnetworkreachabilitystatusnotreachable://No network (off-grid)
NSLog (@ "No network (off-Grid)");
Break

Case Afnetworkreachabilitystatusreachableviawwan://Phone comes with network
NSLog (@ "Mobile phone comes with network");
Break

Case Afnetworkreachabilitystatusreachableviawifi://WIFI
NSLog (@ "WIFI");
Break
}
}];

3. Start monitoring
[Mgr Startmonitoring];

Seven. What is the difference between ASI and AFN?
1. Performance (Focus)
* ASI based on the underlying cfnetwork framework
* AFN based on nsurlconnection
* Operating performance: ASI > ASN

2. Processing server data
1> AFN: Automatic parsing based on data returned by the server
* The server returns JSON data, automatically converted to nsdictionary or Nsarray
* The server returns XML data and is automatically converted to Nsxmlparser

2> ASI: Does not parse the server data, directly returns the NSData binary data

3. Process of processing requests
1> afn:success and failure two blocks
2> ASI: There are 3 ways to handle the request process (proxy method \sel\block)

Features of 3.ASI (emphasis)
1> Cache

2> Download and upload
* Easy monitoring of Request progress
* Easy to implement breakpoint download (ASI does not have breakpoint upload function, breakpoint upload to use socket technology)

3> provides a number of expansion interfaces (such as data compression)
* ASIDataCompressor.h
* ASIDataDecompressor.h

4> asihttprequest inherit from Nsoperation
* All requests can be managed uniformly by queue
* Requests can depend on each other

5> Asinetworkqueue
* Unified management of all requests
* 5 downloads \ Upload Request-Asinetworkqueue: Monitor total progress of 5 requests
* Listen for all requests start \ Fail \ Complete
* Shouldcancelallrequestsonfailure
YES: A request in the queue failed and all other requests were canceled
No: One of the requests in the queue failed, the other requests are not affected, and the request continues

Features of 4.AFN
1> Easy to use
2> comes with a network monitoring function

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.