Saturday, October 15, 2011

Control auto rotation only for 'Landscape' or 'Portrait' in iOS.



When other view controller is used both views. You want to use one view controller only use as 'Landscape' or 'Portrait'.

Call this 'setupOneRotation' method in viewWillAppear: (as [self setupOneRotation];)




BOOL            startWithLandscape;



#pragma mark autoRotation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)setupOneRotation
{
    if (self.view.frame.size.width < self.view.frame.size.height) {
       
        nameOfAppDelegate* sharedApplication = (nameOfAppDelegate *)[[UIApplication  sharedApplication] delegate];       // More details for this, use this link
       
       
        startWithLandscape = YES;
       
        [UIView beginAnimations:@"View Flip" context:nil];
        [UIView setAnimationDuration: 0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
       
        sharedApplication.window.transform = CGAffineTransformIdentity;
       
       
        UIInterfaceOrientation toInterfaceOrientation = self.interfaceOrientation; // get current interface orientation
        //

        if (toInterfaceOrientation == UIInterfaceOrientationPortrait){
            sharedApplication.window.transform = CGAffineTransformMakeRotation(-M_PI/2);
           
            [[UIApplication sharedApplication]
             setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:YES];
        }else if (toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
            sharedApplication.window.transform = CGAffineTransformMakeRotation(M_PI/2);
           
            [[UIApplication sharedApplication]
             setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:YES];
           
        }
       
        sharedApplication.window.bounds = CGRectMake(0.0f, 0.0f, 1024.0f, 768.0f);
        sharedApplication.window.center  = CGPointMake (384.0, 512.0);

        [UIView commitAnimations];
    }
}

- (void) viewWillDisappear:(BOOL)animated
{
    if (startWithLandscape) {
       
       
        nameOfAppDelegate* sharedApplication = (nameOfAppDelegate *)[[UIApplication  sharedApplication] delegate];
        [UIView beginAnimations:@"View Flip" context:nil];
        [UIView setAnimationDuration: 0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
       
        sharedApplication.window.transform = CGAffineTransformIdentity;
            //sharedApplication.window.transform = CGAffineTransformMakeRotation(M_PI/2);
        sharedApplication.window.bounds = CGRectMake(0.0f, 0.0f, 768.0f, 1024.0f);
        sharedApplication.window.center  = CGPointMake (384.0, 512.0);
       
        [UIView commitAnimations];
    }
   
    [super viewWillDisappear: NO];
}

Recognize your Tap in iPhone


 Using this, you can recognize tap in the View.
 
- (void)viewWillAppear:(BOOL)animated
{


    UIGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];

        //tapScroll.numberOfTapsRequired = 2;     //here we can give tap count also

    [recognizeTapView addGestureRecognizer:tapScroll];
    tapScroll.delegate = self;
   
    [tapScroll release];
}


- (void)handleTap:(UITapGestureRecognizer *)recognizer
{
           // After recognize tap, here you can implement code.      
}

Use HTML page on UIWebView in iPhone


   
You can use this method for complex User Interface in iPhone View Controller. Because we can create ".html" page easily and use this method to display complex UI 
    UIWebView *webView = [[UIWebView alloc] init];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
    [webView setUserInteractionEnabled:YES];
//    [webView setScalesPageToFit:YES];
    [self.view addSubview:webView];
    [webView release];

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