My Blog List

Android FirstAid Coding

A Small Help From a Small Heart
Powered by Blogger.

A software professional, who still likes to code, likes to blog and loves gadgets.

Saturday 7 September 2013

Back to Application after end of the call in iPhone

 

By using openURL we can make phone call from our app.


Problem:


It takes the users to the default Phone application after end of the call. But the users needs to go back to the app after end of the call.


Solution


NSString *phFormat=[NSString stringWithFormat:@"telprompt://0123456789"];           
[UIApplication sharedApplication] openURL:[NSURL URLWithString:phFormat]];

Splash Screen Animation on iPhone

How to show splash screen in iphone with a animation
 

AppDelegate.m
==============
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:viewController.view];
[window makeKeyAndVisible];
[NSTimer scheduledTimerWithTimeInterval:1.0/30. target:self selector:@selector(splashScreen) userInfo:nil repeats:NO];

}

- (void) splashScreen
{
//Welcome Screen
UIImageView* welcome = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)]autorelease];
welcome.image = [UIImage imageNamed:@"myimage.png"];
[window addSubview:welcome];
[window bringSubviewToFront:welcome];
//Animation Effects (zoom and fade)
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:window cache:YES];
[UIView setAnimationDelegate:welcome];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

//set transparency to 0.0
welcome.alpha = 0.0;

//zoom effect
welcome.frame = CGRectMake(-60, -60, 440, 600);
[UIView commitAnimations];

}
 

Sunday 28 July 2013

How to show placeholder in UITextView iPhone

ViewController.h
------------------

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextViewDelegate>{
    UITextView *commentTf;
}

@end

ViewController.m
-----------------

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];   
    commentTf  = [[UITextView alloc] initWithFrame:CGRectMake(7, 40, 306, 85)];   
    [commentTf setFont:[UIFont systemFontOfSize:17.0]];   
    [commentTf setTextColor:[UIColor lightGrayColor]];      
    [commentTf setAutocapitalizationType:UITextAutocapitalizationTypeSentences];     
    commentTf.delegate=self;
    commentTf.text =@"Write your comment here";   
    [self.view addSubview:commentTf];

}
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
    if (commentTf.textColor == [UIColor lightGrayColor]) {
        commentTf.text = @"";
        commentTf.textColor = [UIColor blackColor];
    }   
    return YES;
}
-(void) textViewDidChange:(UITextView *)textView
{
    if(commentTf.text.length == 0){
        commentTf.textColor = [UIColor lightGrayColor];
        commentTf.text = @"Write your comment here";
        [commentTf resignFirstResponder];
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {   
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        if(commentTf.text.length == 0){
            commentTf.textColor = [UIColor lightGrayColor];
            commentTf.text = @"Write your comment here";
            [commentTf resignFirstResponder];
        }
        return NO;
    }   
    return YES;
}
@end


Thursday 25 July 2013

SQLite Datbase in iPhone


This is the simple iPhone project which is based on  SQLite database.This is very simple way for using SQLite in out iPhone APP.
We have to add a SQLite framework in our project for using database. Do a control-click (right click) on the Frameworks folder. Click Add -> Existing Frameworks. So in the search bar type in libsqlite3. Now add  libsqlite3.0.dylib.
Here i have done all the basic database operation
  • Add/insert
  • Delete
  • Update
  • Retrieve

Demp app is developed in Xcode 4.3.2 and IOS SDK 5


AppDelegate.h
===============
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    sqlite3 *contactDB;
    NSString *databasePath;
    NSString *relinkUserId;
}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end
Create the database structure in AppDelegate once

AppDelegate.m
===============
#import "AppDelegate.h"

#import "ViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self createDb];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
   
    self.window.rootViewController = navController;
   
 
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)createDb{
    NSString *docsDir;
    NSArray *dirPaths;
   
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    docsDir = [dirPaths objectAtIndex:0];
   
    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"Test.db"]];
   
    NSFileManager *filemgr = [NSFileManager defaultManager];
   
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];
       
        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT,EMAIL TEXT)";
           
            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog( @"Failed to create STUDENT table");
            }           
           
            sqlite3_close(contactDB);
           
        } else {
            NSLog( @"Failed to open/create database");
        }
    }
   
}


@end

ViewController.h
================
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@interface ViewController : UIViewController{
    IBOutlet UITextField *nameTf,*phoneTf,*emailTf,*addressTf;
    NSString *name,*phone,*email,*address,*databasePath;
     sqlite3 *contactDB;
   
   
}
@property(nonatomic,retain)NSString *name,*phone,*email,*address;
-(IBAction)save:(id)sender;

@end


ViewController.m
===================
How to save/insert data.

-(IBAction)save:(id)sender{
   
    name=nameTf.text;
    phone=phoneTf.text;
    email=emailTf.text;
    address=addressTf.text;
   
   databasePath=[self dataBasePath];
    // NSFileManager *filemgr = [NSFileManager defaultManager];
    sqlite3_stmt    *statement;
   
    const char *dbpath = [databasePath UTF8String];
   
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
       
            NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO STUDENT (name, address, phone,email) VALUES (\"%@\", \"%@\", \"%@\",\"%@\")", name, address, phone,email];
           
            const char *insert_stmt = [insertSQL UTF8String];           
            sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
           
      
       
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSInteger lastRowId = sqlite3_last_insert_rowid(contactDB);
            NSLog(@"lastRowId==%d",lastRowId);
           
           
        }else {
            NSLog(@"Failed to add contact");
            NSLog(@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(contactDB));
        }
       
        sqlite3_finalize(statement);
        sqlite3_close(contactDB);
    }   
   
}

-(NSString *)dataBasePath{
    NSString *docsDir;
    NSArray *dirPaths;
   
   
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    docsDir = [dirPaths objectAtIndex:0];
   
    // Build the path to the database file
    return [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"Test.db"]];
   
}



How to retrieve data from table
==========

-(void)readStudentlist{
   self.studentList=[[NSMutableArray alloc] init];
    // NSFileManager *filemgr = [NSFileManager defaultManager];
    const char *dbpath = [[self dataBasePath] UTF8String];
    if(sqlite3_open(dbpath , &contactDB) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        const char *sqlStatement = "select * from STUDENT order by NAME asc";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(contactDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row
                int rowID = sqlite3_column_int(compiledStatement, 0);
                //NSLog(@"primaryKey==%d",primaryKey);
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSString *aAdd = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSString *aPh = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                NSString *aEmail = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
               
                NSLog(@"%@",aName);
               
                CustomerVO *vo = [[CustomerVO alloc] init];   
                vo.sName=aName;
                vo.sAddress=aAdd;
                vo.sPhone=aPh;
                vo.sEmail=aEmail;
                vo.sId=rowID;
                [self.studentList addObject:vo];
             }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);
       
    }
    sqlite3_close(contactDB);  
  
}


Delete a specific data
======================
-(void)deleteStudent:(int)rowId{

    const char *dbpath = [[self dataBasePath] UTF8String];
    sqlite3_stmt    *statement;
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *deleteSQL = [NSString stringWithFormat: @"delete from STUDENT where id=%d",rowId];
       
        const char *del_stmt = [deleteSQL UTF8String];
       
        sqlite3_prepare_v2(contactDB, del_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            //[self dismissModalViewControllerAnimated:YES];
            //NSInteger lastRowId = sqlite3_last_insert_rowid(contactDB);
            NSLog(@"deleted folder");
           
        } else {
            NSLog(@"Failed to add contact");
            NSLog(@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(contactDB));
        }
        sqlite3_finalize(statement);
        sqlite3_close(contactDB); 
    }
}



CustomerVO.h
=============
#import <Foundation/Foundation.h>
@interface CustomerVO : NSObject{
NSString *sName;
NSString  *sAddress;
NSString  *sPhone;
NSString  *sEmail;
NSInteger sId;
}
@property (assign, nonatomic) NSInteger sId;
@property (nonatomic, retain) NSString *sName,*sAddress,*sPhone,*sEmail;

@end


CustomerVO.m
=============
#import "CustomerVO.h"
@implementation CustomerVO
@synthesize sName,sAddress,sEmail,sPhone,sId;
@end



SMS-LIKE CHAT BUBBLES ON IPHONE

ShowComment.h
==========
#import <UIKit/UIKit.h>
@interface ShowComment : UITableViewController<UITextFieldDelegate,UITextViewDelegate>{

}
@property (nonatomic,retain) NSMutableArray *commentList;
@property (nonatomic,retain) NSMutableArray *userList;
@end


ShowComment.m
==============

//  Created by Rajendra on 22/07/13.
//
//

#import "ShowComment.h"

#import <QuartzCore/QuartzCore.h>
@interface ShowComment ()

@end

@implementation ShowComment
@synthesize commentList,userList;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad]; 
    self.commentList=[[NSMutableArray alloc] initWithObjects:@"Hello",@"Hi",@"How are you?",@"Great..& u ?",@"Fine.Why didn't you come lastday? ",@"I was sick", nil];
    self.userList=[[NSMutableArray alloc] initWithObjects:@"Raju",@"Rabi",@"Raju",@"Rabi",@"Raju",@"Rabi", nil];
    if ([self.tableView respondsToSelector:@selector(backgroundView)])
        self.tableView.backgroundView = nil;
    UIImageView *bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"inter_bg.jpg"]];
    [self.tableView setBackgroundView:bg];
   
    self.navigationItem.title=@"Bubble Demo";
   
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
  
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  
     int count=[self.commentList count];
   
            return count;
 
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSInteger unameTag = 1;
    static NSInteger msgTag = 2;   
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];   
  
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:CellIdentifier] ;
       
        cell.accessoryType = UITableViewCellAccessoryNone;
        UITextView *userName = [[UITextView alloc] init];
        userName.backgroundColor = [UIColor clearColor];
        userName.editable = NO;
        userName.scrollEnabled = NO;
        [userName sizeToFit];
        userName.tag=unameTag;
        [cell.contentView addSubview:userName];
       
        UITextView *msgText = [[UITextView alloc] init];
        msgText.backgroundColor = [UIColor clearColor];
        msgText.editable = NO;
        msgText.scrollEnabled = NO;
        [msgText sizeToFit];
        msgText.tag=msgTag;
        [cell.contentView addSubview:msgText];   
    }
    UITextView *uTv = (UITextView *)[cell.contentView viewWithTag:unameTag];
    UITextView *msgTv = (UITextView *)[cell.contentView viewWithTag:msgTag];   
  
    CGFloat result = 20.0;
    CGFloat result1 = 20.0;
    CGSize textSize = { 230.0, 20000.0 };
   
    NSString *oneUsername=[self.userList objectAtIndex:indexPath.section];
    NSString *oneComment=[self.commentList objectAtIndex:indexPath.section];   
    CGSize size = [ oneComment sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
    CGSize size1 = [ oneUsername sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];   
    result = MAX(size.height - 5.0, 30.0);
    result1 = MAX(size1.height - 5.0, 30.0);
   
    uTv.text=oneUsername;
    msgTv.text=oneComment;
   
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];   
    [cell setFrame:CGRectMake(0, 0, size.width, size.height)];   
    if ( indexPath.section % 2 == 0 ) {
        [uTv setFrame:CGRectMake(5.0, 35.0, 50.0, result1)];
        [msgTv setFrame:CGRectMake(70.0, 10.0, size.width+30, result)];
       
        UIImage* balloon = [[UIImage imageNamed:@"bubbleSomeone.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
        UIImageView *newImage = [[UIImageView alloc] initWithFrame:CGRectMake(50.0, 0.0, size.width+55, result+20)];
        UIView *newView =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.frame.size.width, cell.frame.size.height)];
       
        [newImage setImage:balloon];
        [newView addSubview:newImage];
        [cell setBackgroundView:newView];   
    }
    else
    {
        [uTv setFrame:CGRectMake(265.0, 35.0, 50.0, result1)];
        [msgTv setFrame:CGRectMake(220.0-size.width, 10.0, size.width+30, result)];
        UIImage* balloon = [[UIImage imageNamed:@"bubbleMine.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
        UIImageView *newImage = [[UIImageView alloc] initWithFrame:CGRectMake(210.0-size.width, 0.0, size.width+55, result+20)];
        UIView *newView =[[UIView alloc] initWithFrame:CGRectMake(0, 0.0, cell.frame.size.width, cell.frame.size.height)];
       
        [newImage setImage:balloon];
        [newView addSubview:newImage];
        [cell setBackgroundView:newView];
    }
  
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {   
    if ([self.commentList count] != 0) {       
        CGSize textSize = { 260.0, 20000.0 };       
        NSString *oneComment=[self.commentList objectAtIndex:indexPath.section];       
        CGSize size = [oneComment sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
        size.height += 5;       
        CGFloat height = size.height<36?36:size.height;       
        return height;
    }
    return 80;   
}

@end







bubbleMine.png


bubbleOther.png  
Download Project

Tuesday 23 July 2013

Push notification in IOS

One thing you should know that IOS apps use different provisioning profiles for development and distribution.So push server certificates are different for development and distribution:
    •    Development. If your app is running in Debug mode and is signed with the Development provisioning profile (Code Signing Identity is “iPhone Developer”), then your server must be using the Development certificate.
    •    Production. Apps that are distributed as Ad Hoc or on the App Store (when Code Signing Identify is “iPhone Distribution”) must talk to a server that uses the Production certificate. If there is a mismatch between these, push notifications cannot be delivered to your app.


Steps for Push notification for development.

----------------------------------------------------
Generating the Certificate Signing Request (CSR)
The first step to using the APNs is to generate a certificate request file so that you can use it to request for a development SSL certificate later on.
1. Launch the Keychain Access application in your Mac OS X.
2. Select Keychain Access => Certificate Assistant => Request a Certificate From a Certificate Authority
3.Enter the information required and check the Saved to disk option. Click Continue
4.Save the certificate by clicking Save.
5.It will save as "CertificateSigningRequest" with ".certSigningRequest" extension.

Creating an App ID
Each iPhone applications that uses the push notification must have a unique application ID

Step 1: Login to iOS Provisioning Portal, click "Identifiers" on the right side. Make sure "App IDs" is selected, then click "+" button.

Step 2: Enter a short description of your app, check "Push Notification" service option, fill the "Bundle ID" field for App ID Suffix. For Bundle ID, we suggest you to use a reverse-domain name style string, e.g if your domain is "rajuandroid.com", enter "com.rajuandroid.yourAppName". Then, click "Continue" button to go to next step.

Step 3: Confirm your App ID information, then click "Submit" button to complete the registration.

Creating SSL Certificate

 
Step 1: Login to iOS Provisioning Portal, click "Certificates" on the left navigation bar. Then, click "+" button.

Step 2: Select Apple Push Notification service SSL (Sandbox) option under Development section, then click "Continue" button.

Step 3: Select the App ID you want to use for your BYO app , then click "Continue" to go to next step.

Step 4: Upload the ".certSigningRequest" file which is generated before, then click "Generate" button.

Step 5: Click "Done" to finish the registration, the iOS Provisioning Portal Page will be refreshed.

Step 6: Then Click "Download" button to download the certificate (.cer file) you've created just now

Step 7: Double click the downloaded file to install the certificate into Keychain Access on your Mac.


Step 8: On your Mac, go to "Keychain", look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with "Apple Development IOS Push Services:" followed by your app's bundle ID.

Step 9: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the "Cmd" key on your keyboard, right click (or cmd-click if you use a single button mouse), choose "Export 2 items".

Step10:Then save the p12 file with name "DevelopmentPushCer.p12" to your Desktop.Now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.

Creating PEM file

Step 11: Open "Terminal" on your Mac, and run the following commands:
cd
cd Desktop
openssl pkcs12 -in DevelopmentPushCer.p12 -out DevelopmentPushCer.pem -nodes -clcerts

Enter Import Password:
(Enter same password whatever given just above steps)
Step 12:Now "DevelopmentPushCer.pem" file will be created in your desktop.This .pem file is required for the server side implementation.


IOS code
==========
Now write some code in IOS app so that we can obtain a device token.When your app registers for remote (push) notifications, it tries to obtain a “device token”.
This is a 32-byte number that uniquely identifies your device.
e.g of device token
<740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad>

Step1:Make sure that you are using a development profile for Code Signing build settings.

Step2:Open AppDelegate.m. Change the application:didFinishLaunchingWithOptions: method to look like this

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

    return YES;
}


Step3:In order to be able to receive push notifications. Add the following to AppDelegate.m:


 - (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    //NSLog(@"APNS device token is: %@", deviceToken);
  
    NSString *tokenStr = [deviceToken description];
    NSString *pushToken = [[tokenStr
                              stringByReplacingOccurrencesOfString:@"<" withString:@""]
                             stringByReplacingOccurrencesOfString:@">" withString:@""]
                            ;

   // NSLog(@"pushToken is: %@", pushToken);
//write your code to send this pushToken to your server.so that your server can send notification to this device.
       
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}




ServerSide code
============
Implement some code for sending push notification.

Thursday 18 July 2013

Storing small data in IOS using NSUserDefaults

NSUserDefaults
1. Storing Data
// create a standardUserDefaults variable NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
// saving an NSString
[standardUserDefaults setObject:@"mystring" forKey:@"string"];

// saving an NSInteger
[standardUserDefaults setInteger:42 forKey:@"integer"];

// saving a Double
[standardUserDefaults setDouble:3.1415 forKey:@"double"];

// saving a Float
[standardUserDefaults setFloat:3.1415 forKey:@"float"];

// synchronize the settings
[standardUserDefaults synchronize];
2. Retrieving Data
// create a standardUserDefaults variable NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
// getting an NSString object
NSString *myString = [standardUserDefaults stringForKey:@"keyToLookupString"];

// getting an NSInteger object
NSInteger myInt = [standardUserDefaults integerForKey:@"integerKey"];
// getting an Float object
float myFloat = [standardUserDefaults floatForKey:@"floatKey"];

Wednesday 17 July 2013

How to start a thread in IOS

//Start an activity indicator here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //Call your function or whatever work that needs to be done
    //Code in this part is run on a background thread
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        //Stop your activity indicator or anything else with the GUI
        //Code here is run on the main thread
    });
});

Friday 12 July 2013

How to show multiple UITextField within UIalertView ios

Create alertview to show

UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Please enter" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];

    [dialog setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];   
    [[dialog textFieldAtIndex:1] setSecureTextEntry:NO];
    [[dialog textFieldAtIndex:0] setPlaceholder:@"User Name"];
    [[dialog textFieldAtIndex:1] setPlaceholder:@"Email Id"];
    [dialog show];


This is the delegate method to catch the user input

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{    
         [alertView dismissWithClickedButtonIndex:0 animated:YES];
        if (buttonIndex == 0) {
           //cancel clicked
        }else {
                     
            NSString *name = [[alertView textFieldAtIndex:0].text stringByTrimmingCharactersInSet:
                    [NSCharacterSet whitespaceCharacterSet]];   
            NSString *email = [[alertView textFieldAtIndex:1].text stringByTrimmingCharactersInSet:
                     [NSCharacterSet whitespaceCharacterSet]];
           
        }      

}


Thursday 11 July 2013

Add Multiple Buttons in the UINavigation Bar in iOS

UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc]
                                     initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                     target:self
                                     action:@selector(deleteAction:)];
    deleteButton.style = UIBarButtonItemStyleBordered;
    UIBarButtonItem  *saveButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                   target:self
                  action:@selector(saveAction:)];
    saveButton.style = UIBarButtonItemStyleBordered;
   
    // create a spacer between the buttons
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                               target:nil
                               action:nil];
   
    NSArray *myButtonArray = [[NSArray alloc] initWithObjects:deleteButton, saveButton,spacer, nil];
    self.navigationItem.rightBarButtonItems = myButtonArray;



Wednesday 26 June 2013

File management in iPhone

This topic is based on file management in iPhone.Here is the code snippet which
able to perform below action.

    •    Creating a folder in document directory

    •    Creating folder within folder(subfolder) inside document directory
    •    Copy file from Nsbundle to Document directory
    •    Access the contents of a document folder
    •    Access the file name,file path & file updated time of a document folder
    •    Copy a file from one folder to another folder within document directory
    •    Delete a file
    •    Move the contents of a folder to another folder within document directory  

How to view the file system on the iOS simulater?

open finder => Go =>(Then click "Alt" key to see the "Library") => Library => Application Support => iPhone Simulator

It has directories for all models of simulators (4.0, 4.1, 5.0, etc) you have ever run, go to the one you are running from in Xcode.
Once in a folder, go to Applications, choose the Finder option that shows date for files, and sort by date. Your application will be the most recent since it just changed the directory.
Inside the directory is everything related to your application.


Creating a folder in document directory
-(void)createFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
       
        NSError* error;
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Folder Created Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create raju directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
}


Creating folder within folder(subfolder) inside document directory

-(void)createSubFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Raju1/Raju2/Raju3"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
       
        NSError* error;
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error]){
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Folder Created Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create raju directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
}

Copy file from Nsbundle to Document directory

-(void)copyNsbundleFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *storePath = [documentsDirectory stringByAppendingPathComponent:@"Raju/myphoto.jpg"];
   
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:storePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"me1" ofType:@"jpg"];
       
        if (defaultStorePath) {
            NSError* error;
            if(  [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:&error]){
                UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"File Copied Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [Alert show];
            }                  
            else
            {
                NSLog(@"[%@] ERROR: attempting create raju directory", [self class]);
                NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
            }
           
        }
    }
}






Access the contents of a document folder

-(void)contentOfFolder{
    NSError* error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
   
    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error];
    NSLog(@"conent of a folder===%@",filesArray);
}






Access the file name,file path & file updated time of a document folder


-(void)contentOfFolderWithFileInfo{
    NSError* error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
   
    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error];
    //NSLog(@"conent of a folder===%@",filesArray);
    for(NSString* file in filesArray) {
        NSString* filePath = [folderPath stringByAppendingPathComponent:file];
       
        NSDictionary* properties = [[NSFileManager defaultManager]
                                    attributesOfItemAtPath:filePath
                                    error:&error];
        NSDate* modDate = [properties objectForKey:NSFileModificationDate];
        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
        [dateFormatter1 setDateFormat:@"dd/MM/YY HH:mm"];
        NSLog(@"File Name==%@",file);
        NSLog(@"File update date==%@",[dateFormatter1 stringFromDate:modDate]);
        NSLog(@"File Path==%@",filePath);
       
    } 
}




Copy a file from one folder to another folder within document directory

-(void)copyFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *actualImagePath = [documentsDirectory stringByAppendingPathComponent:@"Raju/myphoto.jpg"];
    NSString *copyImagePath = [documentsDirectory stringByAppendingPathComponent:@"Meera/Adi"];
    NSError* error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:copyImagePath]){     
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:copyImagePath withIntermediateDirectories:YES attributes:nil error:&error]){           
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
    NSFileManager *manager = [NSFileManager defaultManager];   
    if([manager copyItemAtPath:actualImagePath toPath:[NSString stringWithFormat:@"%@/myphoto.jpg",copyImagePath] error:&error]==NO)
    {
        UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@",[error userInfo]] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [Alert show];
    }else {
       
        NSLog(@"image copied");
       
    }
}


Delete a file

-(void)removeFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *deleteFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Meera/Adi"];
    NSError* error;
    NSFileManager *manager = [NSFileManager defaultManager];   
   
    if(![manager removeItemAtPath: deleteFolderPath error:&error]) {
        NSLog(@"Delete failed:%@", error);
    } else {
        NSLog(@"folder removed: %@", deleteFolderPath);
    }
    UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"File Moved Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [A
lert show];
}


Move the contents of a folder to another folder within document directory

-(void)moveFile{
    NSError *error=nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *existingFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
   
    NSString *toPath = [documentsDirectory stringByAppendingPathComponent:@"Meera"];//folder named meera already exist in my case
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![[NSFileManager defaultManager] fileExistsAtPath:toPath]){     
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:toPath withIntermediateDirectories:NO attributes:nil error:&error]){           
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
   
    NSArray *allImagePath = [manager contentsOfDirectoryAtPath:existingFolderPath error:nil];
    for (NSString *onepath in allImagePath){
        NSString *actualImagePath=[NSString stringWithFormat:@"%@/%@",existingFolderPath,onepath];
        if ([manager moveItemAtPath:actualImagePath toPath:[NSString stringWithFormat:@"%@/%@",toPath,onepath] error:&error] != YES)
        {
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@",[error userInfo]] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }else {
           
            NSLog(@"File Moved");
        }
    }
}


Download Project