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
78
79
80
81
82
83
84
85
#import "Downloader.h"

@implementation Downloader

@synthesize strFileNameWithPath;
@synthesize delegate;


-(void)loadData{

    floatTotalData = 100;
    floatReceivedData = 0;

    self.strFileNameWithPath        = [[NSHomeDirectory() stringByAppendingPathCompoanent:@"Documents"] stringByAppendingPathComponent:@"tmp"];
    self.strFileNameWithPath        = [self.strFileNameWithPath  stringByAppendingPathComponent:@"someFile.zip"];

    [[NSFileManager defaultManager] createFileAtPath:self.strFileNameWithPath contents:nil attributes:nil];

    NSMutableURLRequest *request    = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://url.com/getData.php"]];


    //this block shall show how to add POST variables to the request
    NSString *encodedParameterPairs    = [NSString stringWithFormat:@"uid=%@", [[UIDevice currentDevice] uniqueIdentifier]];
    NSData *requestData                = [encodedParameterPairs dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    [request setHTTPMethod: @"POST"];
    [request setHTTPBody:requestData];

    [NSURLConnection connectionWithRequest:request delegate:self]; //request is send here
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //store how big file is going to be
    floatTotalData = [[NSString stringWithFormat:@"%lli",[response expectedContentLength]] floatValue];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    floatReceivedData += [data length];


    //add new data to the end of the file
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath: self.strFileNameWithPath];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData: data];
    [fileHandle closeFile];


   //if delegate did implement the method didReceiveData let him know about the new data
    if ([self.delegate respondsToSelector:@selector(didReceiveData:)])
        [self.delegate didReceiveData:self];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {


  //do something with the received data....

  //and let the delegate know that the download has finished

  if ([self.delegate respondsToSelector:@selector(didLoadData:)])
        [self.delegate didLoadData:self];
}


-(float)getProgressInPercent{

   //if you want to show a progressbar or something similar call this method in

   //the delegate method didReceiveData
    return (floatReceivedData / floatTotalData) * 100.0f;
}

- (void)dealloc {
   //free memory
    [strFileNameWithPath release], strFileNameWithPath = nil;
    delegate = nil;

    [super dealloc];
}

@end