RSS

UIViewController lifecycle in iOS

While browsing stackoverflow.com site , I found this nice post about UIViewController lifecycle in iOS.  I like the image showing lifecycle. So I thought its worth to share here.

Image

 
Leave a comment

Posted by on July 17, 2013 in Uncategorized

 

Tags:

Display Images in PageControl iphone

// .h file

#import <UIKit/UIKit.h>

@interface PageControlSampleViewController : UIViewController <UIScrollViewDelegate> {

UIScrollView *scrollView;
UIPageControl *pageControl;
BOOL pageControlUsed;
UIImageView *imageView;
}

@property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
@property (nonatomic, retain) IBOutlet UIPageControl *pageControl;
@property (nonatomic, readwrite) BOOL pageControlUsed;
@property (nonatomic, retain) UIImageView *imageView;

– (IBAction)changePage:(id)sender;

@end

 

 

// . m file

 

#import “PageControlSampleViewController.h”

@implementation PageControlSampleViewController

@synthesize scrollView;
@synthesize pageControl;
@synthesize pageControlUsed;
@synthesize imageView;

– (void)viewDidLoad
{
[super viewDidLoad];

pageControlUsed = NO;
self.scrollView.delegate = self;

NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor],[UIColor greenColor],[UIColor cyanColor], nil];

for (int i=0; i<[colors count]; i++) {

CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;

UIView *subView = [[UIView alloc]initWithFrame:frame];
[subView setBackgroundColor:[colors objectAtIndex:i]];

//add imageview
imageView = [[UIImageView alloc]init];
CGRect imageFrame;
imageFrame.origin.x = 10;
imageFrame.origin.y = 10;
imageFrame.size.width = 250;
imageFrame.size.height = 250;
imageView.frame = imageFrame;

[subView addSubview:imageView];

switch (i) {
case 0:
imageView.image = [UIImage imageNamed:@”silverapple41.png”];
break;
case 1:
imageView.image = [UIImage imageNamed:@”silverapple42.png”];
break;
case 2:
imageView.image = [UIImage imageNamed:@”silverapple43.png”];
break;
default:
break;
}

[imageView setBackgroundColor:[UIColor whiteColor]];
[self.scrollView addSubview:subView];
[subView release];
}

self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * [colors count], self.scrollView.frame.size.height);
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = colors.count;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {

if (!pageControlUsed) {
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x – pageWidth / 2 ) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
}

– (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlUsed = NO;
}

– (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlUsed = NO;
}

// valueChanged event
– (IBAction)changePage:(id)sender {

CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
pageControlUsed = YES;

}

 
1 Comment

Posted by on December 28, 2011 in ios

 

UIImagePickerController in iphone

First add following delegate  & ivar in header file

<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

UIImagePickerController * picker;

UIImageView *imageView;

In .m file

-(IBAction) getPhoto:(id) sender {
       if (picker == nil) {
              picker = [[UIImagePickerController alloc] init];
       }
       picker.delegate = self;
       picker.allowsEditing = YES;

       if((UIButton *) sender == btnCamera) {

             if( [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront] || [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear])
             {
                    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
             }
             else {
                    [self showAlertViewWithTitle:@"Sorry" message:@"Your Device Don't Have Camera"];
             }
        }
        else {
               picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        [self presentModalViewController:picker animated:YES];

}

#pragma mark - image Picker Delegate Method
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
     [self.picker dismissModalViewControllerAnimated:YES];
     //Since we kept allowsEditing = YES , we use UIImagePickerControllerEditedImage else use UIImagePickerControllerOriginalImage
     imageView.image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker
{
     [[currentPicker parentViewController] dismissModalViewControllerAnimated:YES];
}
 
2 Comments

Posted by on December 4, 2011 in ios

 

Tags: ,

Dynamic UILabel Height in iphone

Many times we need dynamic height UILabel in ios appliaction. Below code show you how to achieve this

+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width :(UILineBreakMode)lineBreakMode
{
       [text retain];
       [withFont retain];
       
       CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];

       [text release];
       [withFont release];

       return suggestedSize.height;
}

 
Leave a comment

Posted by on December 4, 2011 in ios

 

iAd on iphone

This is a link for tutorial

 

 

 
Leave a comment

Posted by on December 4, 2011 in ios

 

SQlite on iphone

// SQLiteDBConnection.h

#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import “Mobile.h”

@interface SQLiteDBConnection : NSObject {

NSString *dbPath;
NSString *dbName;
}

@property (nonatomic, retain) NSString *dbPath;
@property (nonatomic, retain) NSString *dbName;

-(NSString*)getDatabasePath;
-(void) checkAndCreateDatabase;
-(NSMutableArray*)readAllMobileFromDatabase;
-(void) addNewMobile:(Mobile*)mobile;

@end

//SQLiteDBConnection.m

#import “SQLiteDBConnection.h”
#import “Mobile.h”

@implementation SQLiteDBConnection

@synthesize dbName;
@synthesize dbPath;

-(NSString*)getDatabasePath {

dbName = @”mobile.sqlite”;

// get the path of documents directory
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirPath = [documentPaths objectAtIndex:0];
dbPath = [docDirPath stringByAppendingPathComponent:dbName];
return dbPath;
}

-(void) checkAndCreateDatabase {

BOOL success;

NSFileManager *fileManager = [NSFileManager defaultManager];

// chk if db is copied at documents dir
success = [fileManager fileExistsAtPath:[self getDatabasePath]];

if (success)
return;

// if not then copy db file
NSString *dbFromApp = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:dbName];

[fileManager copyItemAtPath:dbFromApp toPath:[self getDatabasePath] error:nil];
[fileManager release];
}

-(NSMutableArray*)readAllMobileFromDatabase {

sqlite3 *database;

// init the array
NSMutableArray *mobileArray = [[NSMutableArray alloc]init];

//chk if db is copied @ documents directory
[self checkAndCreateDatabase];

// open db
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

//setup sql stmt
const char *sqlStmt = “select * from mobile”;
sqlite3_stmt *compiledStmt;

if (sqlite3_prepare_v2(database, sqlStmt, -1, &compiledStmt, NULL) == SQLITE_OK) {

// loop through the results & add them in array
while (sqlite3_step(compiledStmt) == SQLITE_ROW) {

// when you use SELECT , index starts from 1
NSString *mCompany = [NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStmt, 1)];
NSString *mModel = [NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStmt, 2)];
double mPrice = sqlite3_column_double(compiledStmt, 3);

// create mobile object & init with data then add it to array & finally release it
Mobile *mobile = [[Mobile alloc]initMobileWithCompany:mCompany model:mModel price:mPrice];
[mobileArray addObject:mobile];
[mobile release];
}
}

// release compiled stmt from memory
sqlite3_finalize(compiledStmt);
}
// close db
sqlite3_close(database);

// return records array

return mobileArray;

}

-(void)addNewMobile:(Mobile*)mobile {

sqlite3 *database;

[self checkAndCreateDatabase];

if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

const char *sqlStatement = “insert into mobile(company,model,price) Values(?, ?,?)”;
sqlite3_stmt *compiledStatement;

if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)    {

sqlite3_bind_text( compiledStatement, 1, [mobile.company UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text( compiledStatement, 2, [mobile.model UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_double(compiledStatement, 3, [mobile price]);

}

if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {

NSLog( @”Error: %s”, sqlite3_errmsg(database) );
}

else {
NSLog( @”Data Inserted successfully”);

}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);

}

-(void)deleteAllRecordsFromDB
{

[self checkAndCreateDatabase];
sqlite3 *database;

if(sqlite3_open([sqliteConnect.databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sqlStatement = “Delete from mobile”;
sqlite3_stmt *compiledStatement;

if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(compiledStatement))
{
NSLog(@”Error while deleting data. ‘%s'”, sqlite3_errmsg(database));
}
NSLog(@”Delete Done”);
sqlite3_finalize(compiledStatement);
}
}
sqlite3_close(database);
[sqliteConnect release];
}

-(void) dealloc {

[dbPath release];
[dbName release];
[super dealloc];
}

@end

Here is my Mobile class

// Mobile.h

@interface Mobile : NSObject {

NSString *company;
NSString *model;
double price;

}

@property (nonatomic, retain) NSString *company;
@property (nonatomic, retain) NSString * model;
@property (nonatomic, readwrite) double price;

-(id)initMobileWithCompany:(NSString*)comp model:(NSString *)model price:(double)price;

// Mobile.m

@implementation Mobile

@synthesize company;
@synthesize model;
@synthesize price;

-(id)initMobileWithCompany:(NSString*)comp model:(NSString *)mdl price:(double)pri {

self.company = comp;
self.model = mdl;
self.price = pri;
return self;
}

-(void)dealloc {

[company release];
[super dealloc];
}

 
Leave a comment

Posted by on December 2, 2011 in ios

 

Tags: ,

Integrate Google Maps in iphone application

Here is a link to the tutorial on GoogleMaps on iphone

 
Leave a comment

Posted by on November 30, 2011 in ios

 

Tags: , , ,

Working with UIGestureRecognizers

UIGestureRecognizers were introduced in iOS 3.0, way back when it was called iPhone OS. UIGestureRecognizer is an abstract class that several concrete classes extend Eg. UITapGestureRecognizer, UIPinchGestureRecognizer.

This is a post in which you can learn about UIGestureRecognizers.

Here is a link to tutorial.

 
Leave a comment

Posted by on November 30, 2011 in ios

 

Tags: ,

Parsing XML Files in iphone or ipad

Introduction

NSXMLParser is a forward only reader or an event driven parser. What it means is, an event is raised whenever the parser comes across a start of an element, value, CDATA and so on. The delegate of NSXMLParser can then implement these events to capture XML data. Some of the events are raised multiple times like the start of an element, value of an element and so on. Since NSXMLParser is known as an event driven parser, we can only read data at the present node and cannot go back. The iPhone only supports NSXMLParser and not NSXMLDocument, which loads the whole XML tree in memory.

I learn the XML parsing from iphonesdkarticles website.

Here is the link for the tutorial.

 
Leave a comment

Posted by on November 30, 2011 in ios

 

Tags: ,