UIDownloadBar.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // UIDownloadBar.m
  3. // UIDownloadBar
  4. //
  5. // Created by John on 3/20/09.
  6. // Copyright 2009 Gojohnnyboi. All rights reserved.
  7. //
  8. #import "UIDownloadBar.h"
  9. @implementation UIDownloadBar
  10. @synthesize DownloadRequest,
  11. DownloadConnection,
  12. receivedData,
  13. delegate,
  14. percentComplete;
  15. - (UIDownloadBar *)initWithURL:(NSURL *)fileURL progressBarFrame:(CGRect)frame timeout:(NSInteger)timeout delegate:(id<UIDownloadBarDelegate>)theDelegate {
  16. self = [super initWithFrame:frame];
  17. if(self) {
  18. self.delegate = theDelegate;
  19. bytesReceived = percentComplete = 0;
  20. localFilename = [[[fileURL absoluteString] lastPathComponent] copy];
  21. receivedData = [[NSMutableData alloc] initWithLength:0];
  22. self.progress = 0.0;
  23. self.backgroundColor = [UIColor clearColor];
  24. DownloadRequest = [[NSURLRequest alloc] initWithURL:fileURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:timeout];
  25. DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self startImmediately:YES];
  26. if(DownloadConnection == nil) {
  27. [self.delegate downloadBar:self didFailWithError:[NSError errorWithDomain:@"UIDownloadBar Error" code:1 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"NSURLConnection Failed", NSLocalizedDescriptionKey, nil]]];
  28. }
  29. }
  30. return self;
  31. }
  32. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  33. [self.receivedData appendData:data];
  34. NSInteger receivedLen = [data length];
  35. bytesReceived = (bytesReceived + receivedLen);
  36. if(expectedBytes != NSURLResponseUnknownLength) {
  37. self.progress = ((bytesReceived/(float)expectedBytes)*100)/100;
  38. percentComplete = self.progress*100;
  39. }
  40. [delegate downloadBarUpdated:self];
  41. }
  42. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  43. [self.delegate downloadBar:self didFailWithError:error];
  44. }
  45. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  46. expectedBytes = [response expectedContentLength];
  47. }
  48. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  49. [self.delegate downloadBar:self didFinishWithData:self.receivedData suggestedFilename:localFilename];
  50. }
  51. - (void)drawRect:(CGRect)rect {
  52. [super drawRect:rect];
  53. }
  54. - (void)dealloc {
  55. }
  56. @end