Saturday, October 15, 2011

UIProgressView (bar) for an NSURLConnection when downloading a file in iPhone


When call to the - (void)downloadTheme method, you can use this Object


MCSecondLoadingScreen.h File


#import "UIKit/UIKit.h"
#import "eCommerceAppDelegate.h"

@class eCommerceAppDelegate;

@interface MCSecondLoadingScreen : UIViewController "UIAlertViewDelegate"
{

    UILabel                    *loadingText;
    UIActivityIndicatorView *activityView;
    UIButton                *skipButton;
    UIProgressView            *progressBar;
   
   
    NSURLConnection            *urlConnection;
    double                    fileLength;
    double                    lastProgress;
    double                    currentLength;
    id                        parent;
    NSOutputStream            *fileStreem;
}
@property (nonatomic, retain) IBOutlet UILabel                    *loadingText;
@property (nonatomic, retain) IBOutlet UIActivityIndicatorView    *activityView;
@property (nonatomic, retain) IBOutlet UIButton                    *skipButton;
@property (nonatomic, retain) IBOutlet UIProgressView            *progressBar;

@property (assign) id parent;

- (IBAction)skipButtonTapped;

- (void)showProgress;
- (void)downloadTheme;
- (void)extractTheme;
- (void)deleteZipFile;

@end


 MCSecondLoadingScreen.h File


#import "MCSecondLoadingScreen.h"
#import "ZipArchive.h"

#define kThemeFileName    @"theme.zip"

@implementation MCSecondLoadingScreen
@synthesize loadingText;
@synthesize activityView;
@synthesize skipButton;
@synthesize progressBar;

@synthesize parent;

- (IBAction)skipButtonTapped
{
    [urlConnection cancel];
   
    [fileStreem close];
    [self deleteZipFile];
    [parent loadTabBarController];
}

- (void)showProgress
{
    [activityView stopAnimating];
    [activityView setHidden:YES];
   
    [progressBar setHidden:NO];
    [skipButton setHidden:NO];
    loadingText.text = NSLocalizedString(@"Loading Theme", @"Loading Theme");
}

- (void)downloadTheme
{
    NSURL *url = [[NSURL alloc] initWithString:@"http://download.macromedia.com/pub/flashplayer/updaters/10/flashplayer_10_sa_debug.app.zip"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [url release];
   
    urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    [request release];
   
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *themePath = [documentsDirectory stringByAppendingPathComponent:kThemeFileName];
    fileStreem = [[NSOutputStream alloc] initToFileAtPath:themePath append:YES];
    [fileStreem open];
}

- (void)extractTheme
{
    [activityView startAnimating];
    [activityView setHidden:NO];
   
    skipButton.hidden = YES;
    progressBar.hidden = YES;
    loadingText.text = NSLocalizedString(@"Extracting Theme", @"Extracting Theme");
   
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *themePath = [documentsDirectory stringByAppendingPathComponent:kThemeFileName];
   
    if (themePath) {
       
        //unzip the file
        ZipArchive* za = [[ZipArchive alloc] init];
        if( [za UnzipOpenFile:themePath] ){
           
            if([za UnzipFileTo:documentsDirectory overWrite:YES])
            {
               
            }
            [za UnzipCloseFile];
        }
       
        [za release];
        NSFileManager *fm = [NSFileManager defaultManager];     // delete zip file
        [fm removeItemAtPath:themePath error:nil];
        [fm removeItemAtPath:[documentsDirectory stringByAppendingPathComponent: @"__MACOSX"] error:nil];
       
    }   
        //update theme count in database.
   
    [parent loadTabBarController];
}

- (void)deleteZipFile
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *themePath = [documentsDirectory stringByAppendingPathComponent:kThemeFileName];
   
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:themePath error:nil];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    fileLength = 1.0;
    lastProgress = 0.0;
    currentLength = 0.0;
}
 

- (void)didReceiveMemoryWarning
{

    [super didReceiveMemoryWarning];
   
}

- (void)viewDidUnload
{
    self.loadingText = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    activityView = nil;
    loadingText = nil;
    skipButton = nil;
    progressBar = nil;
}


- (void)dealloc
{
    [loadingText release];
    [activityView release];
    [skipButton release];
    [progressBar release];
    [fileStreem release];
    [super dealloc];
}

#pragma mark -
#pragma mark URLConnection Delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    long length = [response expectedContentLength];
    fileLength = length;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{   
    double length = [data length];
    currentLength += length;
    double progress = currentLength/fileLength;
   
    if (lastProgress < progress) {
        progressBar.progress = progress;
        lastProgress = progress;
    }
   
   
    NSUInteger left = [data length];
    NSUInteger nwr = 0;
    do {
        nwr = [fileStreem write:[data bytes] maxLength:left];
        if (-1 == nwr) break;
        left -= nwr;
    } while (left > 0);
    if (left) {
        NSLog(@"stream error: %@", [fileStreem streamError]);
    }
   
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Connection Failed", @"Connection Failed")
                                                    message:NSLocalizedString(@"Theme downloading Failed", @"Theme downloading Failed"
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"OK", @"OK"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    [fileStreem close];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    progressBar.progress = 1.0;
    [fileStreem close];
    [self extractTheme];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [self deleteZipFile];
    [parent loadTabBarController];
}

@end

 

No comments:

Post a Comment

Add your comment