Asihttprequest series (II): file download.

Source: Internet
Author: User

4. Download

1. Simple download

Open IB, drag a progress view, declare it as iboutlet in the source file, and then connect.

-(Ibaction) gourl {

Nsstring * Path = [nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes) objectatindex: 0];

Path = [path stringbyappendingpathcomponent: @ "plsqldev714.rar"];

Nsurl * url = [nsurl urlwithstring: @ "http: // localhost/upload/plsqldev714.rar"];

Asihttprequest * request = [asihttprequest requestwithurl: url];

[Request setdownloaddestinationpath: path];

[Request setdownloadprogressdelegate: progressview];

[Request startsynchronous];

}

Run the program. The download progress is displayed in progress view. The download progress shows the approximate proportion of the current completion.

2. Use the queue to download and display the progress bar

A queue is a nsoperationqueue object. It is actually a multi-threaded operation. It can execute multiple download tasks at the same time, or even download the same task with multiple threads (of course, it must be supported by the server, divides the same file resource into multiple threads for simultaneous download, and then merges it into a file ). In the following example, we use nsoperationqueue for multiple download tasks at the same time, and the progress view shows the exact progress.

In this example, You need to design the interface. For ease of use, we use the IB design interface.

Create a viewcontroller class. Add-> new file, select uiviewcontroller subclass, and check "with XIB for user interface". Name it queueviewcontroller.

Open the XIB file with IB, and drag 6 uilable, 1 uibutton, and 3 uiprogressview:

Declare necessary variables and iboutlet/ibaction in xcode:

# Import <uikit/uikit. h>

# Import "asihttprequest. H"

# Import "asinetworkqueue. H"

@ Interface queueviewcontroller: uiviewcontroller {

Asinetworkqueue * networkqueue;

Uilabel * status_total, * status_file1, * status_file2;

Uibutton * button;

Uiprogressview * progress_total, * progress_file1, * progress_file2;

Bool failed;

Nsfilemanager * FM;

}

@ Property (nonatomic, retain) iboutlet uilabel * status_file2, * status_file1, * status_total;

@ Property (nonatomic, retain) iboutlet uibutton * button;

@ Property (nonatomic, retain) iboutlet uiprogressview * progress_file1, * progress_file2, * progress_total;

-(Ibaction) Go :( ID) sender;

@ End

Connect all exits to queueviewcontroller. XIB correctly and save the settings.

Open mainwindow. XIB, drag a uiviewcontroller, change its identifier to queueviewcontroller, and connect it to the rootviewcontroller of the window object.

The code for writing the uibutton touch up inside event is as follows:

-(Ibaction) Go :( ID) sender {

If (fm = nil ){

Fm = [nsfilemanager defamanager manager];

}

Nsstring * userdocpath = [nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes) objectatindex: 0];

// File 1

Nsstring * file1 = @ "image.png ";

Nsurl * url1 = [nsurl urlwithstring: @ "http: // 220.163.103.23/interface/getattach? Accounts = sa & Password = ydtf @ 95598 & attachid = 26 "];

// First create the file file1 and then use nsfilehandle to open it

Nsstring * path1 = [userdocpath stringbyappendingpathcomponent: file1];

Bool B = [FM createfileatpath: path1 contents: Nil attributes: Nil];

Nsfilehandle * fh1;

_ Block uint fsize1 = 0; // in unit B, record the size of the downloaded file, which must be declared as writable.

If (B ){

Fh1 = [nsfilehandle filehandleforwritingatpath: path1];

}

// File 2

Nsstring * file2 = @ "plsqldev714.rar ";

Nsurl * url2 = [nsurl urlwithstring: @ "http: // 220.163.103.23/upload/plsqldev714.rar"];

// First create the file file2 and then use nsfilehandle to open it

Nsstring * path2 = [userdocpath stringbyappendingpathcomponent: file2];

B = [FM createfileatpath: path2 contents: Nil attributes: Nil];

Nsfilehandle * fh2;

_ Block uint fsize2 = 0; // in unit B, record the size of the downloaded file, which must be declared as writable.

If (B ){

Fh2 = [nsfilehandle filehandleforwritingatpath: path2];

}

/// // Task queue ////////// ///////////////////

If (! Networkqueue ){

Networkqueue = [[asinetworkqueue alloc] init];

}

Failed = no;

[Networkqueue Reset]; // The queue is cleared.

[Networkqueue setdownloadprogressdelegate: progress_total]; // set the queue progress bar

[Networkqueue setshowaccurateprogress: Yes]; // precisely displays the progress

[Networkqueue setdelegate: Self]; // sets the proxy object of the queue.

Asihttprequest * request;

//// // Request for file1 //////////////////// //

Request = [asihttprequest requestwithurl: url1]; // set the URL of file 1

[Request setdownloadprogressdelegate: progress_file1]; // download progress bar for file 1

// Set userinfo to identify different request objects

[Request setuserinfo: [nsdictionary dictionarywithobject: file1 forkey: @ "targetpath"];

// Use the complete block to complete the download.

[Request setcompletionblock: ^ (void ){

Nslog (@ "% @ complete! ", File1 );

Assert (fh1 );

// Disable file1

[Fh1 closefile];

}];

// Use the failed block to do something when the download fails.

[Request setfailedblock: ^ (void ){

Nslog (@ "% @ download failed! ", File1 );}

];

// Use the received block to do something when receiving data

[Request setdatareceivedblock: ^ (nsdata * Data ){

Fsize1 + = data. length;

[Status_file1 settext: [nsstring stringwithformat: @ "%. 1f K", fsize1/1000.0];

[Status_total settext: [nsstring stringwithformat: @ "%. 0f %", progress_total. Progress * 100];

If (fh1! = Nil ){

[Fh1 seektoendoffile];

[Fh1 writedata: Data];

}

Nslog (@ "% @: % u", file1, Data. Length );

}];

[Networkqueue addoperation: request];

/// // Request for file2 //////////////////

Request = [[[asihttprequest alloc] initwithurl: url2] autorelease]; // set the URL of file 2

[Request setdownloadprogressdelegate: progress_file2]; // download progress bar for file 2

[Request setuserinfo: [nsdictionary dictionarywithobject: file2 forkey: @ "targetpath"];

// Use the complete block to complete the download.

[Request setcompletionblock: ^ (void ){

Nslog (@ "% @ complete! ", File2 );

Assert (fh2 );

// Disable file2

[Fh2 closefile];

}];

// Use the failed block to do something when the download fails.

[Request setfailedblock: ^ (void ){

Nslog (@ "% @ download failed! ", File2 );

}];

// Use the received block to do something when receiving data

[Request setdatareceivedblock: ^ (nsdata * Data ){

Fsize2 + = data. length;

[Status_file2 settext: [nsstring stringwithformat: @ "%. 1f K", fsize2/1000.0];

[Status_total settext: [nsstring stringwithformat: @ "%. 0f %", progress_total. Progress * 100];

If (fh2! = Nil ){

[Fh2 seektoendoffile];

[Fh2 writedata: Data];

}

}];

[Networkqueue addoperation: request];

[Networkqueue go]; // starts a queue task.

}

The running effect is as follows:

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.