PhoneGap Plugin for downloading URL – All The Code

Have you considered using Appcelerator for your project? File downloads are pretty straightforward plus there are plenty more advantages to running a NATIVE app versus running your app in a web client. Contact us for more information on Appcelerator and why it is the platform we use for all solutions.


See the reasons why I don’t recommend PhoneGap, Appcelerator is the better solution


Complete Project Posted here on GitHub

https://github.com/aaronksaunders/FileDownLoadApp

I created a post a few months ago when I first started playing with PhoneGap and it has gotten alot of hits. I never posted ALL of the code and I have gotten alot of requests for it so here it is, enjoy!!

And I am looking for some consulting work if there are any openings out there, let me know

//
//  PixFileDownload.h
//  FileDownLoadApp
//
//  Created by Aaron saunders on 9/8/10.
//

#import <Foundation/Foundation.h>
#import "PhoneGapCommand.h"


@interface PixFileDownload : PhoneGapCommand {
	NSMutableArray* params;
}

-(void) downloadFile:(NSMutableArray*)paramArray withDict:(NSMutableDictionary*)options;
-(void) downloadComplete;
-(void) downloadFileFromUrlInBackgroundTask:(NSMutableArray*)paramArray;
-(void) downloadFileFromUrl:(NSMutableArray*)paramArray;
@end

//
//  PixFileDownload.m
//  FileDownLoadApp
//
//  Created by Aaron Saunders on 9/8/10.
//

#import "PixFileDownload.h"


@implementation PixFileDownload



-(PhoneGapCommand*) initWithWebView:(UIWebView*)theWebView
{
    self = (PixFileDownload*)[super initWithWebView:theWebView];
    return self;
}



//
// entry point to  the javascript plugin for PhoneGap
//
-(void) downloadFile:(NSMutableArray*)paramArray withDict:(NSMutableDictionary*)options {

	NSLog(@"in PixFileDownload.downloadFile",nil);
	NSString * sourceUrl = [paramArray objectAtIndex:0];
	NSString * fileName = [paramArray objectAtIndex:1];
	//NSString * completionCallback = [paramArray objectAtIndex:2];

	params = [[NSMutableArray alloc] initWithCapacity:2];
	[params addObject:sourceUrl];
	[params addObject:fileName];

	[self downloadFileFromUrl:params];
}

//
// call to excute the download in a background thread
//
-(void) downloadFileFromUrl:(NSMutableArray*)paramArray
{
	NSLog(@"in PixFileDownload.downloadFileFromUrl",nil);
	[self performSelectorInBackground: @selector( downloadFileFromUrlInBackgroundTask ) withObject: paramArray waitUntilDone:NO];
}

//
// downloads the file in the background and saves it to the local documents
// directory for the application
//
-(void) downloadFileFromUrlInBackgroundTask:(NSMutableArray*)paramArray
{
	NSLog(@"in PixFileDownload.downloadFileFromUrlInBackgroundTask",nil);
	NSString * sourceUrl = [paramArray objectAtIndex:0];
	NSString * fileName = [paramArray objectAtIndex:1];

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSData* theData = [NSData dataWithContentsOfURL: [NSURL URLWithString:sourceUrl] ];

	// save file in documents directory
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];

	NSString *newFilePath = [documentsDirectory stringByAppendingString:fileName];

	NSFileManager *fileManager=[NSFileManager defaultManager];
	NSError *error=[[[NSError alloc]init] autorelease];

	BOOL response = [theData writeToFile:newFilePath options:NSDataWritingFileProtectionNone error:&error];

	NSLog(@"file save result %@", response);

    // send our results back to the main thread
    [self performSelectorOnMainThread:@selector(downloadComplete:)
						   withObject:nil waitUntilDone:NO];

	[pool drain];
}

//
// calls the predefined callback in the ui to indicate completion
//
-(void) downloadComplete {
	NSLog(@"in PixFileDownload.downloadComplete",nil);
	NSString * jsCallBack = [NSString stringWithFormat:@"pixFileDownloadComplete('%@');",@"return message to ui"];
	[webView stringByEvaluatingJavaScriptFromString:jsCallBack];
}

- (void)dealloc
{
	if (params) {
		[params release];
	}
    [super dealloc];
}


@end
//
//  pixFileDownload.js
//  FileDownLoadApp
//
//  Created by Aaron saunders on 9/8/10.
//

function PixFileDownload() {
}

PixFileDownload.prototype.downloadFile = function(url,destFileName) {
    PhoneGap.exec("PixFileDownload.downloadFile", url,destFileName);
};

PhoneGap.addConstructor(function() {
	window.fileDownloadMgr = new PixFileDownload();
});


here is how you use the code in the HTML file

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
	<!-- Change this if you want to allow scaling -->
    <meta name="viewport" content="width=default-width; user-scalable=no" />

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">

    <title>FileDownLoadApp</title>

	<!-- iPad/iPhone specific css below, add after your main css >
	<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
	<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />
	-->
	<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
	<script type="text/javascript" charset="utf-8" src="pixFileDownload.js"></script>
    <script type="text/javascript" charset="utf-8">


	// If you want to prevent dragging, uncomment this section
	/*
	function preventBehavior(e)
	{
      e.preventDefault();
    };
	document.addEventListener("touchmove", preventBehavior, false);
	*/

	function onBodyLoad()
	{
		document.addEventListener("deviceready",onDeviceReady,false);
	}

	/* When this function is called, PhoneGap has been initialized and is ready to roll */
	function onDeviceReady()
	{
		// do your thing!
		fileDownloadMgr.downloadFile("http://www.cnn.com","test.html");
	}

    </script>
  </head>
  <body onload="onBodyLoad()">

  </body>
</html>

Leave a Reply

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


seven × 3 =

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=""> <strike> <strong>