iOS breakpoint download

Source: Internet
Author: User

Some uses of download

① for small files, can be downloaded directly, no need to download breakpoints, such as processing.

1-(void) clickdownbtn{2Nsurl *url = [Nsurl urlwithstring:@"https://picjumbo.imgix.net/HNCK8461.jpg?q=40&w=1650&sharp=30"];3     if(Self.imgView.image = =Nil) {4 [self download:url];5     } 6 }7 8 //Download Process9-(void) DownLoad: (Nsurl *) url{TenDispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{ OneNSData *imgdata =[NSData Datawithcontentsofurl:url]; AUIImage *img =[UIImage Imagewithdata:imgdata]; -         if(Imgdata! =Nil) { -Dispatch_sync (Dispatch_get_main_queue (), ^{ theSelf.imgView.image =img; -             }); -         } -     }); +}

It is important to note that in multi-threading, the data processing is in the child thread, and the UI update is in the main thread. If the data is not processed in the sub-thread, then there will be thread blocking, the interface card dead. If you download a picture,

-(void) DownLoad: (Nsurl *) url{    // Data Processing (NSDATA) is carried out in the main thread, so it    will die //  Moreover, this writing is meaningless, originally in the main thread, there is no need to jump to the main thread update UI    nsdata *imgdata = [NSData Datawithcontentsofurl:url];    *img = [UIImage imagewithdata:imgdata];     if (Imgdata! = nil)        {^            {= img;        });}    }

The correct approach is to first open up the child threads and then update the UI on the main thread.

Threading a Child

-(void) DownLoad: (Nsurl *) url{    // Open sub-thread    0),^        { // Operation     });}

Async is asynchronous, sync is synchronous

② for large files, you can use nsurlsession to implement pauses, breakpoint downloads, and so on. As follows:
Listen to download progress, need to implement proxy nsurlsessiondownloaddelegate, in this agent commonly used there are 3 methods

 /*  * is downloaded to call , location is the file temporary address  */-(void ) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask Didfinishdownloadingtourl :(nsurl *  
 /*  * * called after each write to the sandbox , where you can set the progress bar data and other operations * Totalbyteswritten/totalbytesexpectedtowrite, these two are used to monitor the download progress * * @param byteswritten the size of this write * @param Totalbyteswritten has been written to the size of the sandbox * @param totalbytesexpectedtowrite file Total size  */-(void ) Urlsession: (Nsurlsession *) session Downloadtask: ( Nsurlsessiondownloadtask *) Downloadtask Didwritedata: (int64_t) Byteswrittentota lBytesWritten: (int64_t) Totalbyteswrittentotalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite{}  
/* */-(void) Urlsession: (Nsurlsession *) session Downloadtask: ( Nsurlsessiondownloadtask *) downloadtask Didresumeatoffset: (int64_t) Fileoffset expectedtotalbytes: (int64_t) expectedtotalbytes{    }

The sample code is as follows, in. m

/** Label showing progress*/@property (nonatomic,strong) UILabel*Progresslabel;/** Progress Animation*/@property (nonatomic,strong) Uiprogressview*Progressview;/** Download Button*/@property (nonatomic,strong) UIButton*downbtn;/** Download Task*/@property (nonatomic,strong) Nsurlsessiondownloadtask*Downloadtask;/** Cache Data*/@property (nonatomic,strong) NSData*TempData;/** Session*/@property (nonatomic,strong) nsurlsession*session;

Lazy loading of the session as

-(Nsurlsession *) session{    if (!  _session) {        *cfg = [nsurlsessionconfiguration defaultsessionconfiguration];         Delegate : Self delegatequeue:[nsoperationqueue mainqueue]];    }     return _session;}

button Click events are as follows:

//Click the Download button-(void) clickdownbtn{self.downBtn.selected= !self.downBtn.selected; if(Nil = =self.downloadtask) {if(self.tempdata) {[self goondownload];//continue to download}Else{//download starting from 0[self startdownload]; }    } Else{[Self pausedownload]; }}/** Start Download*/-(void) startdownload{Nsurl*url = [Nsurl urlwithstring:@"Http://11.gxdx2.crsky.com/201501/apkok-v3.0.zip"]; //Create a taskSelf.downloadtask =[Self.session Downloadtaskwithurl:url]; //Start Task[Self.downloadtask resume];}/** Pause Download*/-(void) pausedownload{//Prevent circular references__weaktypeof(self) weakself =Self ; [Self.downloadtask cancelbyproducingresumedata:^ (NSData *resumedata) {        //Resumedata contains the start location and URL to continue the downloadWeakself.tempdata =Resumedata; Weakself.downloadtask=Nil; }];}/** Resume Download*/-(void) goondownload{//the data returned from the last pause download can be resumed for downloadSelf.downloadtask =[Self.session DownloadTaskWithResumeData:self.tempData];    [Self.downloadtask resume]; Self.tempdata=Nil;}

Implement 2 proxy methods, the 3rd one is temporarily unavailable

/** Downloaded will be called, location is file temporary address*/-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didfinishdownloadingtourl: (Nsurl *) location{//Select the download file path and the file can only be downloaded to the program's directory//download to Documents folder below, if NSDocumentDirectory is changed to Nscachesdirectory, it will be downloaded to the cache folderNSString *caches =[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject]; //Response.suggestedfilename recommended file name, generally consistent with the server-side nameNSString *file =[Caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; //copy or cut temporary files to the caches folderNsfilemanager *filemanager =[Nsfilemanager Defaultmanager]; //atpath: File path before clipping//Topath: The file path after clipping//because the files are downloaded to the Temp folder, they are deleted after the download is complete, so the location must be moved[FileManager MoveItemAtPath:location.path topath:file Error:nil]; //Prompt Download CompleteUialertview *alert = [[Uialertview alloc] Initwithtitle:@"Download Complete"Message:downloadTask.response.suggestedFilenameDelegate: Self cancelbuttontitle:nil otherbuttontitles:nil];    [Alert show]; [Self performselector: @selector (dismissalert:) Withobject:alert afterdelay:2]; //Gray the Download buttonself.downBtn.selected =NO; Self.downBtn.enabled=NO;}/** * After each write to the sandbox is called, where you can set the progress bar data and other operations * Totalbyteswritten/totalbytesexpectedtowrite, these two are used to monitor the download progress * * @param byteswritten The size of this write * @param totalbyteswritten has been written to the size of the sandbox * @param total size of totalbytesexpectedtowrite file*/-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask Didwritedata: (int64_t) Byteswrittentotalbyteswritten: (int64_t) Totalbyteswrittentotalbytesex Pectedtowrite: (int64_t) totalbytesexpectedtowrite{//Note that the progress, the right side of the equal sign must be cast to double, the progress bar has animation effect, or only after the download is completeSelf.progressView.progress = (float) totalbyteswritten/Totalbytesexpectedtowrite; //set as Percent formNSString *percent = [NSString stringWithFormat:@"Download Progress%0.0f%%", (Double) totalbyteswritten/totalbytesexpectedtowrite* -]; Self.progressLabel.text=percent;}

Some of the points to note:
One
The progress of Uiprogressview is float type, so it should be set to float type, otherwise it will not show animation effect

Self.progressView.progress = (float) totalbyteswritten/totalbytesexpectedtowrite;

The effect:

No casts

self.progressView.progress = Totalbyteswritten/totalbytesexpectedtowrite;

The effect:

Two
Nssearchpathfordirectoriesindomains can be used to get the private file path of the app, which is the list of folders in the sandbox, and gets the array form.

// Get Document Folder NSString *document = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastObject ]; // get the Cache folder NSString *caches = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject];

iOS breakpoint download

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.