Cleaning up experimental bits
Re-creating AFDownloadRequestOperation, now with an API closer to NSURLDownload
This commit is contained in:
parent
ca697ce300
commit
2a1d81a792
6 changed files with 86 additions and 433 deletions
|
|
@ -1,6 +1,6 @@
|
|||
// AFDownloadRequestOperation.h
|
||||
//
|
||||
// Copyright (c) 2012 Peter Steinberger (http://petersteinberger.com)
|
||||
// Copyright (c) 2012 Mattt Thompson (http://mattt.me)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
@ -27,82 +27,42 @@
|
|||
/**
|
||||
`AFDownloadRequestOperation` is a subclass of `AFHTTPRequestOperation` for streamed file downloading. Supports Content-Range. (http://tools.ietf.org/html/rfc2616#section-14.16)
|
||||
*/
|
||||
@interface AFDownloadRequestOperation : AFHTTPRequestOperation
|
||||
@interface AFDownloadRequestOperation : AFURLConnectionOperation {
|
||||
@private
|
||||
NSString *_responsePath;
|
||||
NSError *_downloadError;
|
||||
NSString *_destination;
|
||||
BOOL _allowOverwrite;
|
||||
BOOL _deletesFileUponFailure;
|
||||
}
|
||||
|
||||
/**
|
||||
A String value that defines the target path or directory.
|
||||
|
||||
We try to be clever here and understand both a directory or a filename.
|
||||
The target directory should already be create, or the download fill fail.
|
||||
|
||||
If the target is a directory, we use the last part of the URL as a default file name.
|
||||
*/
|
||||
@property (retain) NSString *targetPath;
|
||||
|
||||
/**
|
||||
A Boolean value that indicates if we should try to resume the download. Defaults is `YES`.
|
||||
|
||||
Can only be set while creating the request.
|
||||
*/
|
||||
@property (assign, readonly) BOOL shouldResume;
|
||||
|
||||
/**
|
||||
Deletes the temporary file if operations is cancelled. Defaults to `NO`.
|
||||
*/
|
||||
@property (assign, getter=isDeletingTempFileOnCancel) BOOL deleteTempFileOnCancel;
|
||||
|
||||
/**
|
||||
Expected total length. This is different than expectedContentLength if the file is resumed.
|
||||
|
||||
Note: this can also be zero if the file size is not sent (*)
|
||||
*/
|
||||
@property (assign, readonly) long long totalContentLength;
|
||||
|
||||
/**
|
||||
Indicator for the file offset on partial downloads. This is greater than zero if the file download is resumed.
|
||||
*/
|
||||
@property (assign, readonly) long long offsetContentLength;
|
||||
|
||||
///----------------------------------
|
||||
/// @name Creating Request Operations
|
||||
///----------------------------------
|
||||
@property (readonly, nonatomic, copy) NSString *responsePath;
|
||||
|
||||
/**
|
||||
Creates and returns an `AFDownloadRequestOperation` object and sets the specified success and failure callbacks.
|
||||
|
||||
@param urlRequest The request object to be loaded asynchronously during execution of the operation
|
||||
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes two arguments: the request sent from the client, and the filePath where the file is saved.
|
||||
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while saving/moving the file. This block has no return value and takes two arguments: the request sent from the client, and the error describing the network or file saving error that occurred.
|
||||
|
||||
@return A new download request operation
|
||||
*/
|
||||
+ (AFDownloadRequestOperation *)downloadOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
targetPath:(NSString *)targetPath
|
||||
shouldResume:(BOOL)shouldResume
|
||||
success:(void (^)(NSURLRequest *request, NSString *filePath))success
|
||||
failure:(void (^)(NSURLRequest *request, NSError *error))failure;
|
||||
|
||||
- (id)initWithRequest:(NSURLRequest *)urlRequest targetPath:(NSString *)targetPath shouldResume:(BOOL)shouldResume;
|
||||
|
||||
/**
|
||||
Deletes the temporary file.
|
||||
|
||||
Returns `NO` if an error happened, `YES` if the file is removed or did not exist in the first place.
|
||||
*/
|
||||
- (BOOL)deleteTempFileWithError:(NSError **)error;
|
||||
|
||||
/**
|
||||
Returns the path used for the temporary file. Returns `nil` if the targetPath has not been set.
|
||||
*/
|
||||
- (NSString *)tempPath;
|
||||
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite;
|
||||
|
||||
/**
|
||||
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. This is a variant of setDownloadProgressBlock that adds support for progressive downloads and adds the
|
||||
|
||||
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the number of bytes read since the last time the download progress block was called, the bytes expected to be read during the request, the bytes already read during this request, the total bytes read (including from previous partial downloads), and the total bytes expected to be read for the file. This block may be called multiple times.
|
||||
|
||||
@see setDownloadProgressBlock
|
||||
*/
|
||||
- (void)setProgressiveDownloadProgressBlock:(void (^)(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile))block;
|
||||
- (BOOL)deletesFileUponFailure;
|
||||
|
||||
/**
|
||||
|
||||
*/
|
||||
- (void)setDeletesFileUponFailure:(BOOL)deletesFileUponFailure;
|
||||
|
||||
|
||||
///**
|
||||
//
|
||||
// */
|
||||
//- (void)setDecideDestinationWithSuggestedFilenameBlock:(void (^)(NSString *filename))block;
|
||||
//
|
||||
///**
|
||||
//
|
||||
// */
|
||||
//- (void)setShouldDecodeSourceDataOfMimeTypeBlock:(BOOL (^)(NSString *encodingType))block;
|
||||
//
|
||||
|
||||
@end
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// AFDownloadRequestOperation.m
|
||||
//
|
||||
// Copyright (c) 2012 Peter Steinberger (http://petersteinberger.com)
|
||||
// Copyright (c) 2012 Mattt Thompson (http://mattt.me)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
@ -22,269 +22,75 @@
|
|||
|
||||
#import "AFDownloadRequestOperation.h"
|
||||
#import "AFURLConnectionOperation.h"
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@interface AFURLConnectionOperation (AFInternal)
|
||||
@property (nonatomic, strong) NSURLRequest *request;
|
||||
@property (readonly, nonatomic, assign) long long totalBytesRead;
|
||||
@end
|
||||
|
||||
typedef void (^AFURLConnectionProgressiveOperationProgressBlock)(NSInteger bytes, long long totalBytes, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile);
|
||||
|
||||
@interface AFDownloadRequestOperation() {
|
||||
NSError *_fileError;
|
||||
}
|
||||
@property (nonatomic, retain) NSString *tempPath;
|
||||
@property (assign) long long totalContentLength;
|
||||
@property (assign) long long offsetContentLength;
|
||||
@property (nonatomic, copy) AFURLConnectionProgressiveOperationProgressBlock progressiveDownloadProgress;
|
||||
@interface AFDownloadRequestOperation()
|
||||
@property (readwrite, nonatomic, copy) NSString *responsePath;
|
||||
@property (readwrite, nonatomic, retain) NSError *downloadError;
|
||||
@property (readwrite, nonatomic, copy) NSString *destination;
|
||||
@property (readwrite, nonatomic, assign) BOOL allowOverwrite;
|
||||
@property (readwrite, nonatomic, assign) BOOL deletesFileUponFailure;
|
||||
@end
|
||||
|
||||
@implementation AFDownloadRequestOperation
|
||||
|
||||
@synthesize targetPath = _targetPath;
|
||||
@synthesize tempPath = _tempPath;
|
||||
@synthesize totalContentLength = _totalContentLength;
|
||||
@synthesize offsetContentLength = _offsetContentLength;
|
||||
@synthesize shouldResume = _shouldResume;
|
||||
@synthesize deleteTempFileOnCancel = _deleteTempFileOnCancel;
|
||||
@synthesize progressiveDownloadProgress = _progressiveDownloadProgress;
|
||||
|
||||
#pragma mark - Static
|
||||
|
||||
+ (AFDownloadRequestOperation *)downloadOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
targetPath:(NSString *)targetPath
|
||||
shouldResume:(BOOL)shouldResume
|
||||
success:(void (^)(NSURLRequest *request, NSString *filePath))success
|
||||
failure:(void (^)(NSURLRequest *request, NSError *error))failure
|
||||
{
|
||||
AFDownloadRequestOperation *requestOperation = [[[self alloc] initWithRequest:urlRequest targetPath:(NSString *)targetPath shouldResume:shouldResume] autorelease];
|
||||
|
||||
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
|
||||
if (success) {
|
||||
success(operation.request, ((AFDownloadRequestOperation *)operation).targetPath);
|
||||
}
|
||||
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
||||
if (failure) {
|
||||
failure(operation.request, error);
|
||||
}
|
||||
}];
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
|
||||
+ (NSString *)cacheFolder {
|
||||
static NSString *cacheFolder;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSString *cacheDir = NSTemporaryDirectory();
|
||||
cacheFolder = [[cacheDir stringByAppendingPathComponent:kAFNetworkingIncompleteDownloadFolderName] retain];
|
||||
|
||||
// ensure all cache directories are there (needed only once)
|
||||
NSError *error = nil;
|
||||
NSFileManager *fileMan = [[NSFileManager alloc] init];
|
||||
if(![fileMan createDirectoryAtPath:cacheFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
|
||||
NSLog(@"Failed to create cache directory at %@", cacheFolder);
|
||||
}
|
||||
[fileMan release];
|
||||
});
|
||||
return cacheFolder;
|
||||
}
|
||||
|
||||
// calculates the MD5 hash of a key
|
||||
+ (NSString *)md5StringForString:(NSString *)string {
|
||||
const char *str = [string UTF8String];
|
||||
unsigned char r[CC_MD5_DIGEST_LENGTH];
|
||||
CC_MD5(str, strlen(str), r);
|
||||
return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
|
||||
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
|
||||
}
|
||||
|
||||
#pragma mark - Private
|
||||
|
||||
- (unsigned long long)fileSizeForPath:(NSString *)path {
|
||||
signed long long fileSize = 0;
|
||||
NSFileManager *fileManager = [[NSFileManager alloc] init]; // not thread safe
|
||||
if ([fileManager fileExistsAtPath:path]) {
|
||||
NSError *error = nil;
|
||||
NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
|
||||
if (!error && fileDict) {
|
||||
fileSize = [fileDict fileSize];
|
||||
}
|
||||
}
|
||||
[fileManager release];
|
||||
return fileSize;
|
||||
}
|
||||
|
||||
#pragma mark - NSObject
|
||||
|
||||
- (id)initWithRequest:(NSURLRequest *)urlRequest targetPath:(NSString *)targetPath shouldResume:(BOOL)shouldResume {
|
||||
if ((self = [super initWithRequest:urlRequest])) {
|
||||
NSParameterAssert(targetPath != nil && urlRequest != nil);
|
||||
_shouldResume = shouldResume;
|
||||
|
||||
// we assume that at least the directory has to exist on the targetPath
|
||||
BOOL isDirectory;
|
||||
if(![[NSFileManager defaultManager] fileExistsAtPath:targetPath isDirectory:&isDirectory]) {
|
||||
isDirectory = NO;
|
||||
}
|
||||
// if targetPath is a directory, use the file name we got from the urlRequest.
|
||||
if (isDirectory) {
|
||||
NSString *fileName = [urlRequest.URL lastPathComponent];
|
||||
_targetPath = [[NSString pathWithComponents:[NSArray arrayWithObjects:targetPath, fileName, nil]] retain];
|
||||
}else {
|
||||
_targetPath = [targetPath retain];
|
||||
}
|
||||
|
||||
// download is saved into a temporal file and remaned upon completion
|
||||
NSString *tempPath = [self tempPath];
|
||||
|
||||
// do we need to resume the file?
|
||||
BOOL isResuming = NO;
|
||||
if (shouldResume) {
|
||||
unsigned long long downloadedBytes = [self fileSizeForPath:tempPath];
|
||||
if (downloadedBytes > 0) {
|
||||
NSMutableURLRequest *mutableURLRequest = [[urlRequest mutableCopy] autorelease];
|
||||
NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
|
||||
[mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
|
||||
self.request = mutableURLRequest;
|
||||
isResuming = YES;
|
||||
}
|
||||
}
|
||||
|
||||
// try to create/open a file at the target location
|
||||
if (!isResuming) {
|
||||
int fileDescriptor = open([tempPath UTF8String], O_CREAT | O_EXCL | O_RDWR, 0666);
|
||||
if (fileDescriptor > 0) {
|
||||
close(fileDescriptor);
|
||||
}
|
||||
}
|
||||
|
||||
self.outputStream = [NSOutputStream outputStreamToFileAtPath:tempPath append:isResuming];
|
||||
|
||||
// if the output stream can't be created, instantly destroy the object.
|
||||
if (!self.outputStream) {
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@synthesize responsePath = _responsePath;
|
||||
@synthesize downloadError = _downloadError;
|
||||
@synthesize destination = _destination;
|
||||
@synthesize allowOverwrite = _allowOverwrite;
|
||||
@synthesize deletesFileUponFailure = _deletesFileUponFailure;
|
||||
|
||||
- (void)dealloc {
|
||||
[_progressiveDownloadProgress release];
|
||||
[_targetPath release];
|
||||
[_responsePath release];
|
||||
[_downloadError release];
|
||||
[_destination release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
#pragma mark - Public
|
||||
|
||||
- (BOOL)deleteTempFileWithError:(NSError **)error {
|
||||
NSFileManager *fileManager = [[NSFileManager alloc] init];
|
||||
BOOL success = YES;
|
||||
@synchronized(self) {
|
||||
NSString *tempPath = [self tempPath];
|
||||
if ([fileManager fileExistsAtPath:tempPath]) {
|
||||
success = [fileManager removeItemAtPath:[self tempPath] error:error];
|
||||
}
|
||||
}
|
||||
[fileManager release];
|
||||
return success;
|
||||
}
|
||||
|
||||
- (NSString *)tempPath {
|
||||
NSString *tempPath = nil;
|
||||
if (self.targetPath) {
|
||||
NSString *md5URLString = [[self class] md5StringForString:self.targetPath];
|
||||
tempPath = [[[self class] cacheFolder] stringByAppendingPathComponent:md5URLString];
|
||||
}
|
||||
return tempPath;
|
||||
}
|
||||
|
||||
|
||||
- (void)setProgressiveDownloadProgressBlock:(void (^)(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile))block {
|
||||
self.progressiveDownloadProgress = block;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLRequestOperation
|
||||
|
||||
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
self.completionBlock = ^ {
|
||||
if([self isCancelled]) {
|
||||
// should we clean up? most likely we don't.
|
||||
if (self.isDeletingTempFileOnCancel) {
|
||||
[self deleteTempFileWithError:&_fileError];
|
||||
}
|
||||
return;
|
||||
}else {
|
||||
// move file to final position and capture error
|
||||
@synchronized(self) {
|
||||
NSFileManager *fileManager = [[NSFileManager alloc] init];
|
||||
[fileManager moveItemAtPath:[self tempPath] toPath:_targetPath error:&_fileError];
|
||||
[fileManager release];
|
||||
}
|
||||
}
|
||||
|
||||
if (self.error) {
|
||||
dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
|
||||
failure(self, self.error);
|
||||
});
|
||||
} else {
|
||||
dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
|
||||
success(self, _targetPath);
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
- (NSError *)error {
|
||||
if (_fileError) {
|
||||
return _fileError;
|
||||
if (_downloadError) {
|
||||
return _downloadError;
|
||||
} else {
|
||||
return [super error];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - NSURLConnectionDelegate
|
||||
#pragma mark -
|
||||
|
||||
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
|
||||
[super connection:connection didReceiveResponse:response];
|
||||
|
||||
// check if we have the correct response
|
||||
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
|
||||
if (![httpResponse isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||
return;
|
||||
}
|
||||
|
||||
// check for valid response to resume the download if possible
|
||||
long long totalContentLength = self.response.expectedContentLength;
|
||||
long long fileOffset = 0;
|
||||
if(httpResponse.statusCode == 206) {
|
||||
NSString *contentRange = [httpResponse.allHeaderFields valueForKey:@"Content-Range"];
|
||||
if ([contentRange hasPrefix:@"bytes"]) {
|
||||
NSArray *bytes = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]];
|
||||
if ([bytes count] == 4) {
|
||||
fileOffset = [[bytes objectAtIndex:1] longLongValue];
|
||||
totalContentLength = [[bytes objectAtIndex:2] longLongValue]; // if this is *, it's converted to 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.offsetContentLength = MAX(fileOffset, 0);
|
||||
self.totalContentLength = totalContentLength;
|
||||
[self.outputStream setProperty:[NSNumber numberWithLongLong:_offsetContentLength] forKey:NSStreamFileCurrentOffsetKey];
|
||||
/**
|
||||
|
||||
*/
|
||||
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite {
|
||||
[self willChangeValueForKey:@"isReady"];
|
||||
self.destination = path;
|
||||
self.allowOverwrite = allowOverwrite;
|
||||
[self didChangeValueForKey:@"isReady"];
|
||||
}
|
||||
|
||||
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
|
||||
[super connection:connection didReceiveData:data];
|
||||
|
||||
if (self.progressiveDownloadProgress) {
|
||||
self.progressiveDownloadProgress((long long)[data length], self.totalBytesRead, self.response.expectedContentLength,self.totalBytesRead + self.offsetContentLength, self.totalContentLength);
|
||||
#pragma mark - NSOperation
|
||||
|
||||
- (BOOL)isReady {
|
||||
return [super isReady] && self.destination;
|
||||
}
|
||||
|
||||
- (void)start {
|
||||
if ([self isReady]) {
|
||||
// TODO Create temporary path
|
||||
self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.destination append:NO];
|
||||
|
||||
[super start];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
|
||||
///**
|
||||
//
|
||||
// */
|
||||
//- (void)setDecideDestinationWithSuggestedFilenameBlock:(void (^)(NSString *filename))block;
|
||||
//
|
||||
///**
|
||||
//
|
||||
// */
|
||||
//- (void)setShouldDecodeSourceDataOfMimeTypeBlock:(BOOL (^)(NSString *encodingType))block;
|
||||
|
||||
@end
|
||||
|
|
|
|||
|
|
@ -120,23 +120,6 @@ extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);
|
|||
*/
|
||||
+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
|
||||
|
||||
///-------------------------------------------------
|
||||
/// @name Configuring Resumeable Streaming Downloads
|
||||
///-------------------------------------------------
|
||||
|
||||
/**
|
||||
|
||||
*/
|
||||
- (void)setOutputStreamDownloadingToFile:(NSString *)path
|
||||
shouldResume:(BOOL)shouldResume;
|
||||
|
||||
/**
|
||||
Deletes the temporary file.
|
||||
|
||||
@return `YES` if the file is successfully removed or did not exist in the first place, otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)deleteTemporaryFileWithError:(NSError **)error;
|
||||
|
||||
///-----------------------------------------------------------
|
||||
/// @name Setting Completion Block Success / Failure Callbacks
|
||||
///-----------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -90,38 +90,6 @@ static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
|
|||
return string;
|
||||
}
|
||||
|
||||
static unsigned long long AFFileSizeForPath(NSString *path) {
|
||||
unsigned long long fileSize = 0;
|
||||
|
||||
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
|
||||
if ([fileManager fileExistsAtPath:path]) {
|
||||
NSError *error = nil;
|
||||
NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:&error];
|
||||
if (!error && attributes) {
|
||||
fileSize = [attributes fileSize];
|
||||
}
|
||||
}
|
||||
|
||||
return fileSize;
|
||||
}
|
||||
|
||||
static NSString * AFIncompleteDownloadDirectory() {
|
||||
static NSString *_af_incompleteDownloadDirectory = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSString *temporaryDirectory = NSTemporaryDirectory();
|
||||
_af_incompleteDownloadDirectory = [[temporaryDirectory stringByAppendingPathComponent:kAFNetworkingIncompleteDownloadDirectoryName] retain];
|
||||
|
||||
NSError *error = nil;
|
||||
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
|
||||
if(![fileManager createDirectoryAtPath:_af_incompleteDownloadDirectory withIntermediateDirectories:YES attributes:nil error:&error]) {
|
||||
NSLog(NSLocalizedString(@"Failed to create incomplete download directory at %@", nil), _af_incompleteDownloadDirectory);
|
||||
}
|
||||
});
|
||||
|
||||
return _af_incompleteDownloadDirectory;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFHTTPRequestOperation ()
|
||||
|
|
@ -129,7 +97,6 @@ static NSString * AFIncompleteDownloadDirectory() {
|
|||
@property (readwrite, nonatomic, retain) NSHTTPURLResponse *response;
|
||||
@property (readwrite, nonatomic, retain) NSError *HTTPError;
|
||||
@property (readwrite, nonatomic, copy) NSString *responseFilePath;
|
||||
@property (readonly) NSString *temporaryFilePath;
|
||||
@end
|
||||
|
||||
@implementation AFHTTPRequestOperation
|
||||
|
|
@ -232,40 +199,6 @@ static NSString * AFIncompleteDownloadDirectory() {
|
|||
}
|
||||
}
|
||||
|
||||
- (void)setOutputStreamDownloadingToFile:(NSString *)path
|
||||
shouldResume:(BOOL)shouldResume
|
||||
{
|
||||
BOOL isDirectory;
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory]) {
|
||||
isDirectory = NO;
|
||||
}
|
||||
|
||||
if (isDirectory) {
|
||||
self.responseFilePath = [NSString pathWithComponents:[NSArray arrayWithObjects:path, [[self.request URL] lastPathComponent], nil]];
|
||||
} else {
|
||||
self.responseFilePath = path;
|
||||
}
|
||||
|
||||
// if (shouldResume) {
|
||||
// unsigned long long downloadedBytes = AFFileSizeForPath(self.temporaryFilePath);
|
||||
// if (downloadedBytes > 0) {
|
||||
// NSMutableURLRequest *mutableURLRequest = [[self.request mutableCopy] autorelease];
|
||||
// [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", downloadedBytes] forHTTPHeaderField:@"Range"];
|
||||
// self.request = mutableURLRequest;
|
||||
// }
|
||||
// }
|
||||
|
||||
self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.temporaryFilePath append:!![self.request valueForHTTPHeaderField:@"Range"]];
|
||||
}
|
||||
|
||||
- (NSString *)temporaryFilePath {
|
||||
return [AFIncompleteDownloadDirectory() stringByAppendingPathComponent:[[NSNumber numberWithInteger:[self.responseFilePath hash]] stringValue]];
|
||||
}
|
||||
|
||||
- (BOOL)deleteTemporaryFileWithError:(NSError **)error {
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
|
|
@ -344,16 +277,4 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
[self.outputStream open];
|
||||
}
|
||||
|
||||
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
|
||||
[super connectionDidFinishLoading:connection];
|
||||
|
||||
if (self.responseFilePath && ![self isCancelled]) {
|
||||
@synchronized(self) {
|
||||
NSString *temporaryFilePath = [AFIncompleteDownloadDirectory() stringByAppendingPathComponent:[[NSNumber numberWithInteger:[self.responseFilePath hash]] stringValue]];
|
||||
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
|
||||
[fileManager moveItemAtPath:temporaryFilePath toPath:self.responseFilePath error:&_HTTPError];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
|
|
|||
|
|
@ -39,11 +39,6 @@ extern NSString * const AFNetworkingOperationDidStartNotification;
|
|||
*/
|
||||
extern NSString * const AFNetworkingOperationDidFinishNotification;
|
||||
|
||||
/**
|
||||
|
||||
*/
|
||||
extern NSString * const kAFNetworkingIncompleteDownloadDirectoryName;
|
||||
|
||||
/**
|
||||
`AFURLConnectionOperation` is an `NSOperation` that implements NSURLConnection delegate methods.
|
||||
|
||||
|
|
@ -80,7 +75,7 @@ extern NSString * const kAFNetworkingIncompleteDownloadDirectoryName;
|
|||
|
||||
@warning Attempting to load a `file://` URL in iOS 4 may result in an `NSInvalidArgumentException`, caused by the connection returning `NSURLResponse` rather than `NSHTTPURLResponse`, which is the behavior as of iOS 5.
|
||||
*/
|
||||
@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDataDelegate, NSStreamDelegate> {
|
||||
@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDataDelegate> {
|
||||
@private
|
||||
signed short _state;
|
||||
BOOL _cancelled;
|
||||
|
|
@ -173,6 +168,10 @@ extern NSString * const kAFNetworkingIncompleteDownloadDirectoryName;
|
|||
*/
|
||||
- (id)initWithRequest:(NSURLRequest *)urlRequest;
|
||||
|
||||
///----------------------------------
|
||||
/// @name Pausing / Resuming Requests
|
||||
///----------------------------------
|
||||
|
||||
- (void)pause;
|
||||
- (BOOL)isPaused;
|
||||
|
||||
|
|
|
|||
|
|
@ -169,10 +169,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
self.request = urlRequest;
|
||||
|
||||
self.outputStream = [NSOutputStream outputStreamToMemory];
|
||||
self.outputStream.delegate = self;
|
||||
|
||||
[self.outputStream setProperty:@"Foo bar" forKey:@"Test"];
|
||||
|
||||
|
||||
self.state = AFHTTPOperationReadyState;
|
||||
|
||||
return self;
|
||||
|
|
@ -548,17 +545,4 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
}
|
||||
}
|
||||
|
||||
#pragma mark - NSStreamDelegate
|
||||
|
||||
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
|
||||
switch (eventCode) {
|
||||
case NSStreamEventErrorOccurred:
|
||||
self.error = [stream streamError];
|
||||
[self cancel];
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue