Network Programming Application scenario in IOS development: JSON data acquisition, network data download.
One: Request JSON data generally in the way of asynchronous request, if the use of synchronous request, it will cause the implementation of the iOS interface block, that is, the interface part in the process of requesting data must wait for the data to load complete.
Steps to get the JSON data:
1. Set the string for the network address: NSString *urlstring = @ "http://www.baidu.com";
2. Create Url:nsurl *url = [Nsurl urlwithstring:urlstring];
3. Create Request: Nsurlrequest *urlrequest = [Nsurlrequest Requestwithurl:url];
4. Send an asynchronous request:
Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];
[Nsurlconnection sendasynchronousrequest:urlrequest queue:queue completionhandler:^ (NSURLResponse *response, NSData *data, Nserror *connectionerror) {
The callback block after the request is sent for processing the requested data
/*
The process of JSON parsing data is done here
*/
}];
To send a sync request:
Nsurlresponse *returnresponse; Save Feedback information
Nserror *error; Save error message
NSData *data = [nsurlconnection sendsynchronousrequest:urlrequest returningresponse:&returnresponse error:& ERROR];
JSON parses data, or looks at the error message, or views the connection feedback information.
Second: The network data of the breakpoint continued to download
Steps to continue the breakpoint:
1. Set the address of the download file on the network server: NSString *fileurl = @ "http://www.baidu.com"; Take Baidu website as an example
2. Set the address of the local save download file: NSString *filesavepath = @ "/users/apple/downloads/1.temp"; Take the path of a Mac to download a folder as an example
3. Implement Start Download function
-(void) startdownload
{
The key start=========================== of #======================= for the continuation of breakpoint
Sets the starting position of the file download, in bytes, starting from 0 by default.
unsigned long long startbytes = 0;
Determine if the file exists and get the location of the total number of breakpoint bytes for the entire downloaded file
if ([[[Nsfilemanager Defaultmanager] Fileexistsatpath:_filepath])
{
Startbytes = [[NSData datawithcontentsoffile:_filepath] length];
}
Else
{
[[Nsfilemanager Defaultmanager] Createfileatpath:_filepath contents:nil Attributes:nil];
}
Create variable urlrequest, ignore cache, request timeout of 10 seconds
Nsmutableurlrequest *mutablerequest=[nsmutableurlrequest Requestwithurl:fileurl CachePolicy: Nsurlrequestreloadignoringlocalandremotecachedata timeoutinterval:10.0f];
Set the request head to set the starting byte position of the file transfer
NSString *rangevalue = [NSString stringwithformat:@ "bytes=%llu-", startbytes]; //Note that the format of the string must be correct, and no less than one character.
[Mutablerequest addvalue:rangevalue forhttpheaderfield:@ "Range"]; The value of the string must be @ "Range".
The key end========================= of #====================== for the continuation of breakpoint
// Establish a connection
nsurlconnection = [nsurlconnection connectionwithrequest:mutablerequest delegate:self];// Once this method is successful, the download is started directly
(Human control initiates the download
connection = [[Nsurlconnection alloc] initwithrequest:mutablerequest delegate:self Startimmediately:no];
[Connection start];)
}
4. Interrupt Download
-(void) pausedownload
{
Cancel Connection operation
[Connection Cancel];
connection = nil;
Close file operation
[Outhandle CloseFile];
Outhandle = nil;
}
#==================== Download Agent <NSURLConnectionDataDelegate> implementation =========
Executes before the data download begins.
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response
{
Open file, start writing data
_outhandle = [Nsfilehandle Filehandleforwritingatpath:_filepath];
Get some information on the download
[Response expectedcontentlength]; The size of the entire download file
[Response MIMEType]; Types of download files
[Response textencodingname]; Download the content character encoding name
[Response suggestedfilename]; The default name of the downloaded file
}
The code that executes when the data is received, which may be executed several times during the download process.
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data
{
Write file operation
[_outhandle Seektoendoffile];
[_outhandle Writedata:data];
or receive data with a variable data type
[Mutabledata Appeddata:data];
}
Perform aftercare after data load is complete
-(void) connectiondidfinishloading: (nsurlconnection *) connection
{
NSLog (@ "Download done!");
[_outhandle CloseFile];
_outhandle = nil;
}
Execute if download error occurs
-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error
{
[_outhandle CloseFile];
_outhandle = nil;
NSLog (@ "Connection on error:%@", Error);
}
Summary: This is just a description of the basic implementation of the breakpoint continuation, if you want to add a progress bar or multi-file queue download implementation, you need to further encapsulate the download function to form a convenient library.
The study of the library will be discussed again next time.
Network Programming for iOS development (request data and breakpoint continuation)