afnetworking realization of the breakpoint continuous transmission

Source: Internet
Author: User

 use afnetworking to implement a breakpoint continuation, pause, continue Afnetworking Stop resuming afnetworking version of the breakpoint:
Platform:ios, ' 7.0 '

Pod "afnetworking", "~> 2.3.0"

Simple ideas: Through the reorganization of Progressblock, Successblock, Requesturl, OutputStream, and then use afnetworking to bring the Pause,resume can be implemented properly.

But there are some problems are also very torture people, file input stream, initialization has encountered a problem,
1.[self.requestoperation setoutputstream:[nsoutputstream OutputStreamToFileAtPath:self.cachePath () Append:yes]
If you append the data from the original file, you will not be able to get data from the OutputStream during the download process.
[Self.requestoperation setoutputstream:[nsoutputstream OutputStreamToFileAtPath:self.cachePath () Append:no]
If not appended, the continuation of the transmission will be covered.

The official documents were not looked at carefully, fortunately, the use of non-append, and then manually synchronize the file and input stream. Methods are as follows

-(void) Readcachetooutstreamwithpath: (nsstring*) path;

2.pause later, Afhttprequestoperation.totalbytesread, still record this before the length of the read, if the resume, this is content-length the change, this time need to progressblock from the group, but also need to totalbyt Esread is set to 0 because it is a private property, so use KVC.

[Self.requestoperation setvalue:@ "0" forkey:@ "Totalbytesread"]; ------------casually put a VC----------------------

#define Vedio @ "http://221.228.249.82/youku/697A5CA0CEB3582FB91C4E3A88/ 03002001004e644fa2997704e9d2a7ba1e7b9d-6cab-79a9-e635-3b92a92b3500.mp4 "

#define PICTURE @ "Http://x1.zhuti.com/down/2012/11/29-win7/3D-1.jpg"

-(ibaction) Download: (ID) sender

{

http://202.102.88.133/youku/657114D0FE44481C592F964ABD/ 030020010053f4ab5fb92a01296a84c7e5a401-0fc6-bd65-4525-706b419e9ea6.mp4

http://b.hiphotos.baidu.com/image/h%3D1200%3Bcrop%3D0%2C0%2C1920%2C1200/sign= B284ea7541a98226a7c12f25bab28262/960a304e251f95ca8888fab6cb177f3e670952b4.jpg

nsstring* Path = [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents/temp"];

NSLog (@ "path =%@", path);

Operation = [[Downloadoperationalloc] init];

[Operationdownloadwithurl:picture

Cachepath:^nsstring *{

return path;

} progressblock:^ (Nsuinteger bytesread,long long Totalbytesread,long long Totalbytesexpectedtoread) {

NSLog (@ "bytesread =%u, Totalbytesread =%llu Totalbytesexpectedtoread =%llu", Bytesread,totalbytesread, Totalbytesexpectedtoread);

Float progress = totalbytesread/(float) totalbytesexpectedtoread;

[Self.progressViewsetProgress:progressanimated:YES];

[self.labelsettext:[nsstringstringwithformat:@ "%.2f%%", progress*100]];

uiimage* image = [UIImageimageWithData:operation.requestOperation.responseData];

[Self.imageViewsetImage:image];

} success:^ (Afhttprequestoperation *operation,id responseobject) {

NSLog (@ "Success");

uiimage* image = [UIImage imageWithData:operation.responseData];

[Self.imageview Setimage:image];

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

NSLog (@ "error =%@", error);

}];

}

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





#import <Foundation/Foundation.h>

#import "AFNetworking.h"

@interface Downloadoperation:nsobject

@property (nonatomic, strong) nsurl* URL;

@property (nonatomic, copy) nsstring* (^cachepath) (void);

@property (nonatomic, strong) afhttprequestoperation* requestoperation;

@property (nonatomic, copy) void (^progressblock) (Nsuinteger Bytesread,long long Totalbytesread,long Longtotalbytesexpectedtoread);

-(void) Downloadwithurl: (ID) URL

CachePath: (nsstring* (^) (void)) Cacheblock

Progressblock: (void (^) (Nsuinteger Bytesread,long long Totalbytesread,long longtotalbytesexpectedtoread)) Progressblock

Success: (void (^) (afhttprequestoperation *operation,id responseobject)) success

Failure: (void (^) (afhttprequestoperation *operation,nserror *error)) failure;

@end



#import "DownLoadOperation.h"

@implementation Downloadoperation

-(void) Downloadwithurl: (ID) URL

CachePath: (nsstring* (^) (void)) Cacheblock

Progressblock: (void (^) (Nsuinteger Bytesread,long long Totalbytesread,long longtotalbytesexpectedtoread)) Progressblock

Success: (void (^) (afhttprequestoperation *operation,id responseobject)) success

Failure: (void (^) (afhttprequestoperation *operation,nserror *error)) failure

{

Self.cachepath = Cacheblock;

Gets the length of the cache

Longlong cachelength = [[Selfclass] CacheFileWithPath:self.cachePath ()];

NSLog (@ "cachelength =%llu", cachelength);

GET request

nsmutableurlrequest* request = [[Selfclass] requestWithUrl:urlRange:cacheLength];

Self.requestoperation = [[Afhttprequestoperationalloc] initwithrequest:request];

[Self.requestoperationsetoutputstream:[nsoutputstreamoutputstreamtofileatpath:self.cachepath () Append:NO]];

Process Flow

[SelfreadCacheToOutStreamWithPath:self.cachePath ()];

[self.requestoperationaddobserver:selfforkeypath:@ "ispaused" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionoldcontext:nil];

Get Progress Block

Self.progressblock = Progressblock;

Reorganization Progress Block

[Self.requestoperationsetdownloadprogressblock:[selfgetnewprogressblockwithcachelength:cachelength]];

Get the success callback block

void (^newsuccess) (afhttprequestoperation *operation,id responseobject) = ^ (Afhttprequestoperation *operation, Idresponseobject) {

NSLog (@ "responsehead =%@", [Operation.responseallheaderfields]);

Success (Operation,responseobject);

};

[Self.requestOperationsetCompletionBlockWithSuccess:newSuccess

Failure:failure];

[Self.requestoperationstart];

}

#pragma mark-Gets the locally cached bytes

+ (Longlong) Cachefilewithpath: (nsstring*) path

{

nsfilehandle* fh = [Nsfilehandlefilehandleforreadingatpath:path];

nsdata* contentdata = [Fhreaddatatoendoffile];

Return contentdata? contentdata.length:0;

}

#pragma mark-Reorganization progress block

-(void (^) (Nsuinteger Bytesread,long long Totalbytesread,long longtotalbytesexpectedtoread)) Getnewprogressblockwithcachelength: (Longlong) cachlength

{

typeof (self) newself =self;

void (^newprogressblock) (Nsuinteger bytesread,long long Totalbytesread,long long totalbytesexpectedtoread) = ^ ( Nsuinteger Bytesread,long long Totalbytesread,long long Totalbytesexpectedtoread)

{

nsdata* data = [NSDatadataWithContentsOfFile:self.cachePath ()];

[self.requestoperationsetvalue:dataforkey:@ "ResponseData"];

Self.requestOperation.responseData =;

Newself.progressblock (bytesread,totalbytesread + cachlength,totalbytesexpectedtoread + cachLength);

};

return newprogressblock;

}

#pragma mark-Read local cache inflow

-(void) Readcachetooutstreamwithpath: (nsstring*) path

{

nsfilehandle* fh = [Nsfilehandlefilehandleforreadingatpath:path];

nsdata* CurrentData = [Fhreaddatatoendoffile];

if (currentdata.length) {

Open stream, write data, no clock out view Streamcode = Nsstreamstatusnotopen

[Self.requestOperation.outputStreamopen];

Nsinteger Byteswritten;

Nsinteger Byteswrittensofar;

Nsinteger datalength = [Currentdatalength];

constuint8_t * databytes = [currentdatabytes];

Byteswrittensofar = 0;

do {

Byteswritten = [Self.requestoperation.outputstreamwrite:&databytes[byteswrittensofar]maxlength:datalength- Byteswrittensofar];

ASSERT (Byteswritten!=0);

if (Byteswritten = =-1) {

Break

} else {

Byteswrittensofar + = Byteswritten;

}

} while (Byteswrittensofar! = datalength);

}

}

#pragma mark-GET request

+ (nsmutableurlrequest*) Requestwithurl: (ID) URL Range: (longlong) length

{

nsurl* Requesturl = [Urliskindofclass:[nsurlclass]]? URL: [Nsurlurlwithstring:url];

nsmutableurlrequest* request = [Nsmutableurlrequestrequestwithurl:requesturl

Cachepolicy:nsurlrequestreloadignoringcachedata

TIMEOUTINTERVAL:5*60];

if (length) {

[Request setvalue:[nsstringstringwithformat:@ "bytes=%lld-", length]forhttpheaderfield:@ "Range"];

}

NSLog (@ "request.head =%@", request.allhttpheaderfields);

return request;

}

#pragma mark-monitoring paused

-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void*) Context

{

NSLog (@ "KeyPath =%@ Changedic =%@", keypath,change);

Paused state

if ([keypathisequaltostring:@ "ispaused"] && [[changeobjectforkey:@ "new"]intvalue] ==1) {

Longlong cachelength = [[Selfclass] CacheFileWithPath:self.cachePath ()];

Pause reading data from file to NSNumber

Cachelength = [[Self.requestOperation.outputStreampropertyForKey:NSStreamFileCurrentOffsetKey] Unsignedlonglongvalue];

NSLog (@ "cachelength =%lld", cachelength);

[self.requestoperationsetvalue:@ "0" forkey:@ "Totalbytesread"];

Reorganization Progress Block

[Self.requestoperationsetdownloadprogressblock:[selfgetnewprogressblockwithcachelength:cachelength]];

}

}

@end


    • Previous Obj-c Language Open

afnetworking realization of the breakpoint continuous transmission

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.