Progress bar of download file on iPhone
Categories: iPhone on Oct.23, 2009
This is a sample UIProgressView subclass that I made that will automatically download a file using various different classes from Foundation, to avoid using the undocumented but present-in-iphone NSURLDownload. Sure, this code isn’t the best, but I like to create things like to this to practice things that I want to learn how to do for an app.
This code is free for you to use for whatever, I could care less. I would suggest taking what’s here however and improving it. If I get some time off school before spring break i’ll make it a lil purdier and reupload.
UIDownloadBar.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | // // UIDownloadBar.h // UIDownloadBar // // Created by John on 3/20/09. // Copyright 2009 Gojohnnyboi. All rights reserved. // #import <UIKit/UIKit.h> @class UIProgressView; @protocol UIDownloadBarDelegate; @interface UIDownloadBar : UIProgressView { NSURLRequest* DownloadRequest; NSURLConnection* DownloadConnection; NSMutableData* receivedData; NSString* localFilename; id<UIDownloadBarDelegate> delegate; long long bytesReceived; long long expectedBytes; float percentComplete; } - (UIDownloadBar *)initWithURL:(NSURL *)fileURL progressBarFrame:(CGRect)frame timeout:(NSInteger)timeout delegate:(id<UIDownloadBarDelegate>)theDelegate; @property (nonatomic, readonly) NSMutableData* receivedData; @property (nonatomic, readonly, retain) NSURLRequest* DownloadRequest; @property (nonatomic, readonly, retain) NSURLConnection* DownloadConnection; @property (nonatomic, assign) id<UIDownloadBarDelegate> delegate; @property (nonatomic, readonly) float percentComplete; @end @protocol UIDownloadBarDelegate<NSObject> @optional - (void)downloadBar:(UIDownloadBar *)downloadBar didFinishWithData:(NSData *)fileData suggestedFilename:(NSString *)filename; - (void)downloadBar:(UIDownloadBar *)downloadBar didFailWithError:(NSError *)error; - (void)downloadBarUpdated:(UIDownloadBar *)downloadBar; @end |
UIDownloadBar.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | // // UIDownloadBar.m // UIDownloadBar // // Created by John on 3/20/09. // Copyright 2009 Gojohnnyboi. All rights reserved. // #import "UIDownloadBar.h" @implementation UIDownloadBar @synthesize DownloadRequest, DownloadConnection, receivedData, delegate, percentComplete; - (UIDownloadBar *)initWithURL:(NSURL *)fileURL progressBarFrame:(CGRect)frame timeout:(NSInteger)timeout delegate:(id<UIDownloadBarDelegate>)theDelegate { self = [super initWithFrame:frame]; if(self) { self.delegate = theDelegate; bytesReceived = percentComplete = 0; localFilename = [[[fileURL absoluteString] lastPathComponent] copy]; receivedData = [[NSMutableData alloc] initWithLength:0]; self.progress = 0.0; self.backgroundColor = [UIColor clearColor]; DownloadRequest = [[NSURLRequest alloc] initWithURL:fileURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheDa ta timeoutInterval:timeout]; DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self startImmediately:YES]; if(DownloadConnection == nil) { [self.delegate downloadBar:self didFailWithError:[NSError errorWithDomain:@"UIDownloadBar Error" code:1 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"NSURLConnection Failed", NSLocalizedDescriptionKey, nil]]]; } } return self; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.receivedData appendData:data]; NSInteger receivedLen = [data length]; bytesReceived = (bytesReceived + receivedLen); if(expectedBytes != NSURLResponseUnknownLength) { self.progress = ((bytesReceived/(float)expectedBytes)*100)/100; percentComplete = self.progress*100; } [delegate downloadBarUpdated:self]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self.delegate downloadBar:self didFailWithError:error]; [connection release]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { expectedBytes = [response expectedContentLength]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self.delegate downloadBar:self didFinishWithData:self.receivedData suggestedFilename:localFilename]; [connection release]; } - (void)dealloc { [localFilename release]; [receivedData release]; [DownloadRequest release]; [DownloadConnection release]; [super dealloc]; } @end |
Similar posts:

October 20th, 2010 on 4:35 am
Can you give an example of how to init a download?
October 20th, 2010 on 3:58 pm
Answer
http://www.developers-life.com/sample-usage-uidownloadbar.html
November 12th, 2010 on 10:54 am
[...] Developers-life.com Also See: Apple’s documentation [...]
December 29th, 2010 on 7:35 am
Thank you very much man. You save my life!
April 18th, 2011 on 5:46 pm
Be careful with this code, it is not very well written.
[connection release];
and
[DownloadConnection release];
release the same connection, therefore twice, a crash is on the way.
There is absolutely no need for DownloadRequest to be a member variable, it only gets used in one place. Better create and release it around NSURLConnection initWithRequest:
the rest is ok, thanks
August 11th, 2011 on 6:52 am
First, Thanks a lot for this excellent tutorial.
Was indeed very helpful.
My question is where does the downloaded file saved to on iPhone/iPad?
Also where will be the location of the downloaded file if we are running the simulator?
August 11th, 2011 on 7:02 am
Hi @Raghunath
>>My question is where does the downloaded file saved to on iPhone/iPad?
Not saved, data sent to method of delegate object
- (void)downloadBar:(UIDownloadBar *)downloadBar didFinishWithData:(NSData *)fileData suggestedFilename:(NSString *)filename;
fileData – it’s your downloaded file
August 11th, 2011 on 12:23 pm
Thank you very much for the update. I was using your app for downloading an XML(With UTf8 encoding and version 1.0) file from our local server.
I used the following code to save the “fileData” and was able to save the file to some default location
2
3
4
5
6
7
8
9
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"xyz.xml"];
NSLog(@"File stored at location : %@", storePath);
// write to file atomically (using temp file)
[fileData writeToFile:storePath atomically:TRUE];
When I open the file I don’t find the same content that was on local server. I see some script tags and comments.
Also tried to Log the “fileData” with the following code
I still get the same result when I print it in the console.
I googled the entire day to implement a file download, but didn’t succeed.
Any help with saving to a file or displaying it in UITextView is appreciated.
October 14th, 2011 on 1:59 pm
Not working on iOS5. :(
October 14th, 2011 on 2:03 pm
This is a great piece of code, please update it for iOS 5.
October 17th, 2011 on 4:09 pm
hey :)
i’m using the download bar in an app, and it does a great job – thank you for that!
at the moment i adjust my app for ios 5 and came accross the same problem: no progress bar is visible.
are there any suggestions on how to get it running under ios 5? thanks a lot in advance!
cheers,
j*
October 17th, 2011 on 4:09 pm
hey :)
i\’m using the download bar in an app, and it does a great job – thank you for that!
at the moment i adjust my app for ios 5 and came accross the same problem: no progress bar is visible.
are there any suggestions on how to get it running under ios 5? thanks a lot in advance!
cheers,
j*
October 17th, 2011 on 5:18 pm
ok, got it working again. there was a bug in my singleton implementation, which is not part of the code here.
cheers,
j*
October 18th, 2011 on 4:50 pm
can you please guide me what was the bug??
October 18th, 2011 on 4:58 pm
Even the sample code provided is not working on iOS 5. :(
October 22nd, 2011 on 1:38 am
I’m using this class in MyTube (available on GitHub). Any news on iOS 5?
October 22nd, 2011 on 11:13 am
Well i’ve figured it out.. :)
Actually there is no problem in this code.. I think there is a glitch in UIKit.
Just recreate the whole UIDownloadbar class, and it works. :)
October 22nd, 2011 on 9:38 pm
just comment next string
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
}
October 23rd, 2011 on 11:57 am
moved to github https://github.com/sakrist/UIDownloadBar
October 24th, 2011 on 11:36 am
Thanks alot Vladimir.. :)
November 26th, 2011 on 5:37 am
hi Vladimir Boychentsov ,
what is the best way to get approx. download time for that particular file
thanx
February 8th, 2012 on 8:49 am
… [Trackback]…
[...] Read More Infos here: developers-life.com/progress-bar-download-file-on-iphone.html [...]…
March 28th, 2012 on 8:26 am
wow
@Raghunath
very thank you!!!
I try solve saving file download
I relly happy