Cocoa File Download using NSURLDownload Sample Code

Cocoa File Download using NSURLDownload Sample Code

Created By: Debasis Das (14-Jan-2015)

In this post we will create a simple Cocoa application to demonstrate file download from a specified URL using NSURLDownload delegate methods and APIs
NSURLDownload-1NSURLDownload-2

//
//  AppDelegate.h
//  KSFileDownload
//
//  Created by Debasis Das on 1/15/15.
//  Copyright (c) 2015 Knowstack. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate,NSURLDownloadDelegate>
@end
//
//  AppDelegate.m
//  KSFileDownload
//
//  Created by Debasis Das on 1/15/15.
//  Copyright (c) 2015 Knowstack. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@property (weak) IBOutlet NSWindow *window;
@property (nonatomic, retain) NSURLResponse *downloadResponse;
@property (nonatomic, assign) long bytesReceived;
@property (nonatomic, assign) IBOutlet NSProgressIndicator *progressIndicator;
@property (weak) IBOutlet NSTextField *downloadURLTextField;
@property (weak) IBOutlet NSTextField *downloadProgressTextField;

@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self.downloadURLTextField setStringValue:@"http://knowstack.com/data1.json"]; //Replace this line with the URL you want to use to test the download progress
}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
}

- (IBAction)startDownloadingURL:(id)sender
{
    // Create the request.
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[self.downloadURLTextField stringValue]]
                                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                                            timeoutInterval:6000.0];
    
    // Create the download with the request and start loading the data.
    NSURLDownload  *theDownload = [[NSURLDownload alloc] initWithRequest:theRequest delegate:self];
    if (!theDownload) {
        // Inform the user that the download failed.
        NSLog(@"The download failed");
    }
}

- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
    NSString *destinationFilename;
    NSString *homeDirectory = NSHomeDirectory();
    destinationFilename = [[homeDirectory stringByAppendingPathComponent:@"Desktop"]
                           stringByAppendingPathComponent:filename];
    [download setDestination:destinationFilename allowOverwrite:NO];
}


- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
    // Dispose of any references to the download object
    // that your app might keep.
    // Inform the user.
    NSLog(@"Download failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)downloadDidFinish:(NSURLDownload *)download
{
    // Dispose of any references to the download object
    // that your app might keep.
    // Do something with the data.
    [self.downloadProgressTextField setStringValue:@"Download Complete"]; //Here we are setting the message that the download is complete
}

- (void)setDownloadResponse:(NSURLResponse *)aDownloadResponse
{
    // downloadResponse is an instance variable defined elsewhere.
    _downloadResponse = aDownloadResponse;
}

- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response
{
    // Reset the progress, this might be called multiple times.
    // bytesReceived is an instance variable defined elsewhere.
    self.bytesReceived = 0;
    // Store the response to use later.
    [self setDownloadResponse:response];
}

- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(unsigned)length
{
    long long expectedLength = [[self downloadResponse] expectedContentLength];
    self.bytesReceived = self.bytesReceived + length;
    
    if (expectedLength != NSURLResponseUnknownLength) {
        // If the expected content length is
        // available, display percent complete.
        double percentComplete = (self.bytesReceived/(float)expectedLength)*100.0;
        [self.progressIndicator setDoubleValue:percentComplete];
        [self.downloadProgressTextField setStringValue:[NSString stringWithFormat:@"%ld of %lld bytes Downloaded",self.bytesReceived,expectedLength]];
    }
     else {
        // If the expected content length is
        // unknown, just log the progress.
        NSLog(@"Bytes received - %ld",self.bytesReceived);
    }
}
@end

The project can be downloaded from KSFileDownload

Posted in Cocoa, Objective C Tagged with: , , ,
2 comments on “Cocoa File Download using NSURLDownload Sample Code
  1. Adrian says:

    Hey Debasis Das,

    this app is super cool !

    Do you think I can create an app like this integrating an applescript code ?

    thank you !

    • Debasis Das says:

      Hi Adrian,

      I think you have to use an editor tool in the background.
      I dont have much experience with Apple Script but if you can trigger open a Editor Tool, Put your contents in the editor (while running in background) and then use the print functionality of the editor it will open the print preview and you can trigger the save as pdf option. That might want.

      In the code that is provided in the sample, I have not made it scriptable. If you are aware of Swift / Cocoa you might want to make this sample app scriptable as well.

      Best Regards
      Debasis

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news