iOS multi-task breakpoint Download afnetworking

Source: Internet
Author: User

#import "DownLoadCell.h"


@implementation Downloadcell

-(Instancetype) Initwithstyle: (Uitableviewcellstyle) style Reuseidentifier: (NSString *) reuseidentifier{

Self = [Superinitwithstyle:style reuseidentifier:reuseidentifier];

if (self) {

_button = [Uibuttonbuttonwithtype:uibuttontypecustom];

[_buttonsettitle:@ "Start" forstate:uicontrolstatenormal];

[_buttonsettitle:@ "suspend" forstate:uicontrolstateselected];

[_button setframe:cgrectmake (200, 0, 100, 40)];

[_buttonsetbackgroundcolor:[uicolorredcolor]];


_lable = [[Uilabelalloc]initwithframe:cgrectmake (0, 0, 100, 40)];

[_lablesetbackgroundcolor:[uicolorcyancolor]];

[Self.contentviewaddsubview:_lable];

[Self.contentviewaddsubview:_button];

}

returnself;

}

@end


--------------------------------------------------------------------------------------------------------------- -------


#import "ViewController.h"

#import "AFNetworking.h"

#import "DownLoadCell.h"


#define KDEFAULTTAG 10


#define URL1 @ "http://124.202.164.13/mp4files/50080000058FFE30/pcdowncc.imgo.tv/a61a08d987a596161f029926d3b4e868 /5470d75f/c1/2014/dianshiju/jinpaihongniang/201410316d64dac6-10c5-43f0-8ade-fc53b0833d35.fhv.mp4 "


#define URL2 @ "http://pcdowncc.imgo.tv/c22b568e89664260ea872330ba774741/552b608f/c1/2014/dianshiju/ Jinpaihongniang/2014103198b69041-6f7a-46fd-b0b5-066937cda764.fhv.mp4 "


@interface Viewcontroller () <UITableViewDataSource,UITableViewDelegate>

{

Nsmutabledictionary *dicoperation;

Uilabel *lable;

Nsarray *downloadurllist;

NSString *downurl;

UITableView *tabview;

}

@end


@implementation Viewcontroller


-(void) Viewdidload {

[Super Viewdidload];

Downloadurllist = [[Nsarray alloc]initwithobjects:url1,url2,nil];

Cgsize size = self.view.frame.size;

Tabview = [[UITableView alloc]initwithframe:cgrectmake (0,20, Size.width, Size.Height) Style:uitableviewstyleplain];

[Tabview setdatasource:self];

[Tabview setdelegate:self];

[Self.view Addsubview:tabview];

Dicoperation = [[Nsmutabledictionary alloc]init];


}


-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexPath{

Downloadcell *cell = [[Downloadcell alloc]init];

[Cell.button Settag:kdefaulttag + indexpath.row];

[Cell.button addtarget:self Action: @selector (Begindown:) forcontrolevents:uicontroleventtouchupinside];

return cell;

}


-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{

return 2;

}


-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexpath{

[Tabview Deselectrowatindexpath:indexpath Animated:yes];

}


-(void) Begindown: (UIButton *) sender{

int downloadtag = (int) Sender.tag-kdefaulttag;

Downurl = [Downloadurllist Objectatindex:downloadtag];

if (!sender.selected) {

[Self startdownload:downloadtag];

}else{

Afhttprequestoperation *currentop = [dicoperation objectforkey:@ (Downloadtag)];

[Currentop pause];

}

sender.selected =!sender.selected;



}

Get the downloaded file size

-(unsigned Longlong) Filesizeforpath: (NSString *) path {

Signed Longlong fileSize = 0;

Nsfilemanager *filemanager = [Nsfilemanager new]; Default is not thread safe

if ([FileManager Fileexistsatpath:path]) {

Nserror *error = nil;

Nsdictionary *filedict = [FileManager attributesofitematpath:path error:&error];

if (!error && filedict) {

FileSize = [Filedict fileSize];

}

}

return fileSize;

}


Start download

-(void) Startdownload: (int) Tag {


NSString *cachedirectory = [Nssearchpathfordirectoriesindomains (Nscachesdirectory,nsuserdomainmask, YES) OBJECTATINDEX:0];

Nsarray *arrurllist = [downurlcomponentsseparatedbystring:@ "/"];

NSString *videoname = [arrurllistobjectatindex:arrurllist.count-1];

NSString *downloadpath = [Cachedirectorystringbyappendingpathcomponent:videoname];

Nsurlrequest *request = [Nsurlrequestrequestwithurl:[nsurlurlwithstring:downurl]];


Check to see if the file has been downloaded part

unsigned longlong downloadedbytes = 0;


if ([[Nsfilemanagerdefaultmanager] fileexistsatpath:downloadpath]) {

Get the downloaded file length

Downloadedbytes = [Selffilesizeforpath:downloadpath];

if (Downloadedbytes > 0) {

Nsmutableurlrequest *mutableurlrequest = [Requestmutablecopy];

NSString *requestrange = [nsstringstringwithformat:@ "bytes=%llu-", downloadedbytes];

[Mutableurlrequest setvalue:requestrangeforhttpheaderfield:@ "Range"];

request = Mutableurlrequest;

}

}

Do not use caching to avoid problems with breakpoint continuation

[[Nsurlcachesharedurlcache] removecachedresponseforrequest:request];

Download request

Afhttprequestoperation *operation = [[Afhttprequestoperationalloc] initwithrequest:request];

Download path

Operation.outputstream = [Nsoutputstreamoutputstreamtofileatpath:downloadpath append:yes];

[Dicoperationsetobject:operation forkey:@ (tag)];

Operation.userinfo = @{@ "KEYOP": @ (TAG)};

Download Progress Callback

__weak afhttprequestoperation *MYOP = operation;

[Operation setdownloadprogressblock:^ (Nsuinteger Bytesread,long long Totalbytesread,long long Totalbytesexpectedtoread) {

Download progress

Float progress = ((float) Totalbytesread + downloadedbytes)/(Totalbytesexpectedtoread + downloadedbytes);

Nsindexpath *indexpath = [Nsindexpath indexpathforrow:[[myop.userinfo objectforkey:@ "keyOp"] intValue] inSection:0];

Downloadcell *cell = (Downloadcell *) [Tabview Cellforrowatindexpath:indexpath];

NSString *str = [nsstring stringwithformat:@ "Download%.4f", progress];

Dispatch_async (Dispatch_get_main_queue (), ^{

NSLog (@ "------------------------%d Cell downloads%@", [[Myop.userinfo objectforkey:@ "KEYOP"] intvalue],str);

[Cell.lable SETTEXT:STR];

});

}];

Success and failure callbacks

[Operation setcompletionblockwithsuccess:^ (Afhttprequestoperation *operation,id responseobject) {

Nsindexpath *indexpath = [Nsindexpath indexpathforrow:[[myop.userinfo objectforkey:@ "keyOp"] intValue] inSection:0];

Downloadcell *cell = (Downloadcell *) [Tabview Cellforrowatindexpath:indexpath];

Dispatch_async (Dispatch_get_main_queue (), ^{

[Cell.button settitle:@ "complete" forstate:uicontrolstateselected];

[Cell.button Setuserinteractionenabled:no];

[Cell.lable settext:@ "100%"];

});

} failure:^ (Afhttprequestoperation *operation, Nserror *error) {


}];

[Operation start];

}




@end




Related Article

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.