简体   繁体   中英

Using AFNetworking to Download File in iOS

I want to be able to download a file using AFNetworking that supports: ProgressBar, Pausing, and Resuming download.

Approaching this on my own I was able to come up with this code, except that it doesn't support pausing or resuming:

-(void)downloadFile:(NSString *)UrlAddress indexPathofTable:(NSIndexPath *)indexPath
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlAddress]];
    NSString *pdfName = [self pdfNameFromURL:UrlAddress];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pdfName];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"Successfully downloaded file to %@", path);
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"Error: %@", error);
    }];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
    {
        //do something in this line with the calculation to cell
        float progress = (float)totalBytesRead / totalBytesExpectedToRead;
        [[NSNotificationCenter defaultCenter] postNotificationName:[NSString stringWithFormat:@"progress-%ld-%ld", (long)indexPath.section, (long)indexPath.row] object:@(progress)]; //Working reporting progress in cellForRowAtIndexPath.
    //NSLog(@"Download = %f", progress);
    }];
        [operation start];
}

Thing is, I don't know how to manage pause & resume.

Looking at their documentation: ( https://github.com/AFNetworking/AFNetworking ) they offer a different approach to download the file:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://www.irs.gov/pub/irs-pdf/fw4.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
    return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

I would expect the "fw4.pdf" to be named properly in my iOS' documents folder. However, this is the logged result:

File downloaded to: file:///Users/myName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/F4C3BC41-70B4-473A-B1F6-D4BC2A6D0A4F/Documents/CFNetworkDownload_ZkSW5n.tmp

The above file IS downloaded but with the weird temp name.

I realize in my own code I'm using a "AFHTTPRequestOperation" object whereas they're using a "AFURLSessionManager".

Any ideas?

- (void)downloadFile{

NSURL *url = [NSURL URLWithString:@"http://198.61.234.81/expris/uploads/attachments/file_1.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
NSProgress *progress;
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

    NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];

    //Here is change
    return [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];

}completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

    [progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL];

    dispatch_async(dispatch_get_main_queue(), ^(void){

        NSLog(@"File downloaded to: %@", filePath);


    });

}];

[downloadTask resume];
[progress addObserver:self
           forKeyPath:@"fractionCompleted"
              options:NSKeyValueObservingOptionNew
              context:NULL];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSProgress *progress = (NSProgress *)object;
NSLog(@"Progress… %f", progress.fractionCompleted);
}

download file:

  NSData* data = [[NSData alloc] initWithContentsOfURL:/*your URL*/];

and later save:

  NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  NSString *path = [documentsDirectory stringByAppendingPathComponent:@"test.pdf"];
  [data writeToFile:path atomically:YES];

Or you read CFNetworkDownload_ZkSW5n.tmp and write with pdf extension:

  NSData* data = [[NSData alloc] initWithContentsOfFile: PathYourFile];
  //save code above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM