[Sample] ~ Downloading Files

Discussion in 'iOS Development' started by gojohnnyboi, Apr 6, 2009.

  1. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    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.

    Credit: iPhone PXL from back in the day. It used a method like this to download files since NSURLDownload came around in 2.0 for AppStore(I'm guessing), and I referenced back to it a few times when I couldn't figure some things out.

    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
    [OBJC]//
    // 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

    Please Register or Log in to view images

    NSURL *)fileURL progressBarFrame

    Please Register or Log in to view images

    CGRect)frame timeout

    Please Register or Log in to view images

    NSInteger)timeout delegate

    Please Register or Log in to view images

    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

    Please Register or Log in to view images

    UIDownloadBar *)downloadBar didFinishWithData

    Please Register or Log in to view images

    NSData *)fileData suggestedFilename

    Please Register or Log in to view images

    NSString *)filename;
    - (void)downloadBar

    Please Register or Log in to view images

    UIDownloadBar *)downloadBar didFailWithError

    Please Register or Log in to view images

    NSError *)error;
    - (void)downloadBarUpdated

    Please Register or Log in to view images

    UIDownloadBar *)downloadBar;

    @end
    [/OBJC]

    [OBJC]//
    // 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

    Please Register or Log in to view images

    NSURL *)fileURL progressBarFrame

    Please Register or Log in to view images

    CGRect)frame timeout

    Please Register or Log in to view images

    NSInteger)timeout delegate

    Please Register or Log in to view images

    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:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:timeout];
    DownloadConnection = [[NSURLConnection alloc] initWithRequest

    Please Register or Log in to view images

    ownloadRequest delegate:self startImmediately:YES];

    if(DownloadConnection == nil) {
    [self.delegate downloadBar:self didFailWithError:[NSError errorWithDomain

    Please Register or Log in to view images

    "UIDownloadBar Error" code:1 userInfo:[NSDictionary dictionaryWithObjectsAndKeys

    Please Register or Log in to view images

    "NSURLConnection Failed", NSLocalizedDescriptionKey, nil]]];
    }
    }

    return self;
    }

    - (void)connection

    Please Register or Log in to view images

    NSURLConnection *)connection didReceiveData

    Please Register or Log in to view images

    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

    Please Register or Log in to view images

    NSURLConnection *)connection didFailWithError

    Please Register or Log in to view images

    NSError *)error {
    [self.delegate downloadBar:self didFailWithError:error];
    [connection release];
    }

    - (void)connection

    Please Register or Log in to view images

    NSURLConnection *)connection didReceiveResponse

    Please Register or Log in to view images

    NSURLResponse *)response {
    expectedBytes = [response expectedContentLength];
    }

    - (void)connectionDidFinishLoading

    Please Register or Log in to view images

    NSURLConnection *)connection {
    [self.delegate downloadBar:self didFinishWithData:self.receivedData suggestedFilename:localFilename];
    [connection release];
    }

    - (void)drawRect

    Please Register or Log in to view images

    CGRect)rect {
    [super drawRect:rect];
    }

    - (void)dealloc {
    [localFilename release];
    [receivedData release];
    [DownloadRequest release];
    [DownloadConnection release];
    [super dealloc];
    }


    @end
    [/OBJC]


    -John
  2. H4CK!NT0SH

    H4CK!NT0SH Banned

    Joined:
    Jun 28, 2009
    Messages:
    159
    Likes Received:
    0
    Device:
    2G iPod touch
    This is great, thanks John. Is it possible to make something like this for uploading files? Thanks again.
  3. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    Uploading files will require you to do FTP, or use HTTP-POST
  4. H4CK!NT0SH

    H4CK!NT0SH Banned

    Joined:
    Jun 28, 2009
    Messages:
    159
    Likes Received:
    0
    Device:
    2G iPod touch
    Ohh, yeah. Makes sense. Thanks.
  5. ZunePod

    ZunePod Banned

    Joined:
    Aug 28, 2008
    Messages:
    1,340
    Likes Received:
    0
    Device:
    iPhone 3G (Black)
    There is no URL in there?
  6. SkylarEC

    SkylarEC Super Moderator Emeritus Staff Member

    Joined:
    Sep 19, 2007
    Messages:
    6,642
    Likes Received:
    129
    You initialize it with the URL. That's not an omission or error.

    The only real gotcha in this sample is that your application will crash if the coder fails to implement any of the delegate methods. If that is the desired effect, the @optional tag should be replaced with @required or simply omitted.

    Alternatively, if you adopt this code, the best solution would be to leave the methods as optional and instead check to see if the delegate responds to the methods before trying to make the delegate perform the methods.
  7. dineshkumarm12

    dineshkumarm12 New Member

    Joined:
    Feb 24, 2010
    Messages:
    3
    Likes Received:
    0
    Device:
    2G iPod touch
    Can u explain me in detail to init downloading files or can u send me the entire Xcode Proj..
    ------------------double post merged------------------
    I tried like this
    UIDownloadBar *dvController1 = [[UIDownloadBar alloc] init];
    NSString *temp1 = [NSString stringWithFormat

    Please Register or Log in to view images

    "%@",txtUrl.text];
    NSURL *temp =[NSURL URLWithString:temp1];
    [dvController1 initWithURL:temp progressBarFrame:LFrame timeout:360 delegate:[dvController1 delegate]];
    but it doesnt works....
  8. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    What are you trying to do? What doesn't work? Be more concise.
    However, I see some flaws in your code:
    1. You can't just reinitialze an object (in this case, the download bar).
    2. WTF? Why are you setting the delegate of a newly initialized object to the delegate of that newly initialized object (obviously nil)? That doesn't make any sense! Even if the delegate were already set, that line would make absolutely nothing happen.
    3. Why are you creating a format string with merely another string inside it? That's a waste of processor time! In this case, you really don't need any deep copies of strings.

    [OBJC]NSURL *url = [NSURL URLWithString: txtUrl.text];

    // You should probably put this in an ivar or something
    UIDownloadBar *dvController1 = [[UIDownloadBar alloc] initWithURL: url progressBarFrame: LFrame timeout: 360 delegate: self];
    [/OBJC]
  9. dineshkumarm12

    dineshkumarm12 New Member

    Joined:
    Feb 24, 2010
    Messages:
    3
    Likes Received:
    0
    Device:
    2G iPod touch
    Hi LaunchD,

    Thanks for the reply,For all the above question real answer is "I am new to iPhone Programming and still learning..."
    Can u send me the full source code to download file from server...So that i can learn from ur code..
    I am helpless...I am trying to download pdf file from server...
  10. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    Sorry, but I don't have the full source code. I just restated your code to make it (theoretically) legal.
    Just try to implement UIDownloadBar correctly (and give GJB some credit!)

Share This Page