Saturday, June 11, 2011

Google Analytics in iPhone SDK

Hello Friends,

Today i would like to introduce one important topic about tracking your iPhone or iPad application with one of the best fee google analytical tool. This facility provides you complete tracking with many more functionalities. This analytical tool let you track any event in your application happens. We can analyze which screens of our application are visited most. And all such information we can access from google's website. We can filter out information for better understanding our application usage world wide.

Google provides different graphs and charts to analyze data. Google analytic SDK provides easy integration with application. We have to just add one framework and one header file which is available here.

Drag framework and header file given in sdk in your project and add the following code.
Import "GNATracker.h" file in App delegate class and write following code in didFinishedLaunching method of App delegate class.

// **************************************************************************
  // PLEASE REPLACE WITH YOUR ACCOUNT DETAILS.
  // **************************************************************************
  [[GANTracker sharedTracker] startTrackerWithAccountID:@"UA-00000000-1"
                                         dispatchPeriod:kGANDispatchPeriodSec
                                               delegate:nil];
  NSError *error;

  if (![[GANTracker sharedTracker] setCustomVariableAtIndex:1
                                                       name:@"iPhone1"
                                                      value:@"iv1"
                                                  withError:&error]) {
    NSLog(@"error in setCustomVariableAtIndex");
  }


Above code initiate your account and connection with google analytics. Now following code will be written at place where event or action should be tracked.

if (![[GANTracker sharedTracker] trackEvent:@"Application iPhone"
                                       action:@"Launch iPhone"
                                        label:@"Example iPhone"
                                        value:99
                                    withError:&error]) {
    NSLog(@"error in trackEvent");
  }

Tuesday, May 31, 2011

Download video from URL and Save it in iPhone SDK

Hello Friends,

Today we will discuss for downloading video from particular URL and save it to application sandbox. Generally video files are vary large, so we need efficient way to perform such task. I used to follow the following method.

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPMethod:@"GET"];
NSError *error;
NSURLResponse *response;

NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *videosFolderPath = [documentFolderPath stringByAppendingPathComponent:@"videos"]; 

Now we need to check that video folder is exist or not. If not, then we will create it.

BOOL isDir;
if (([fileManager fileExistsAtPath:videosFolderPath isDirectory:&isDir] && isDir) == FALSE) {
    [[NSFileManager defaultManager] createDirectoryAtPath:videosFolderPath attributes:nil];
}


NSData *urlData;
NSString *downloadPath = @"http://foo.com/videos/bar.mpeg";
[request setURL:[NSURL URLWithString:downloadPath]];
urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *filePath = [videosFolderPath stringByAppendingPathComponent:@"bar.mpeg"];
BOOL written = [urlData writeToFile:filePath atomically:NO];
if (written)
    NSLog(@"Saved to file: %@", filePath);

Have a nice day !!

Saturday, May 28, 2011

Mail sending fuctionality in iPhone SDK (MFMailComposer)

Hello Friends,

Today we are going to discuss very use full topic in iPhone SDK. Many times we need to send an email from iPhone application. For this functionality apple has provided very good feature of MFMailComposer which is given by apple in iOS.  To integrate mail sending functionality from your application follow the following steps.

  • Add MessageUI.framework in your project.
  • Import following files:
  • #import <MessageUI/MessageUI.h>
    #import <MessageUI/MFMailComposeViewController.h> 
  • Add delegate in your header file like <MFMailComposeViewControllerDelegate>
  • Now write following methods in the implementation file and set send mail action on any button you want.

-(IBAction)btnEmailClick
{
 Class mailclass =(NSClassFromString(@"MFMailComposeViewController"));
 if(mailclass != nil)
 {
  if ([mailclass canSendMail])
  {
   [self displayComposerSheet];
  }
  else
  {
   [self launchMailAppOnDevice];
  }
 }
 else
 {
  [self launchMailAppOnDevice];
 }
}


- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{ 
 switch (result)
 {
  case MFMailComposeResultCancelled:
  {
   break;
  }
  case MFMailComposeResultSaved:
  {
   UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"Mail successfully saved!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
   [alert show];
   [alert release];
   break;
  }
  case MFMailComposeResultSent:
  {
   UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"Mail sent successfully!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
   [alert show];
   [alert release];
   break;
  }
  case MFMailComposeResultFailed:
  {
   UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"Mail sending failed!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
   [alert show];
   [alert release];
   break;
  }
  default:
  {
   break;
  }
 }
 [self dismissModalViewControllerAnimated:YES];
}


-(void)displayComposerSheet
{
 MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
 picker.mailComposeDelegate = self;
 [picker setSubject:@""]; 
 NSString *emailBody = @"Hello World";
 [picker setMessageBody:emailBody isHTML:NO];
 
 [self presentModalViewController:picker animated:YES];
    [picker release]; 
}
-(void)launchMailAppOnDevice
{
 NSString *recipients = @"mailto:first@example.com?cc=second@example.com,third@example.com&subject=Hello from California!";
 NSString *body =@"Hello World";
 
 NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
 email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 
 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
 
}

Everything in above code is understandable and easily customizable. So change the code according to your requirements. Yon can set default recipients,subject and mail according to your application requirements. Still if you have any doubts, please feel free to ask me.

Thanks. Enjoy.. :-)

Calculate number of days between two dates in iPhone SDK

Hello Friends,

Today we will focus on another important issue while developing iPhone application. Most of the application contains date picker to select and display date in iPhone. Sometimes it is required to get number of day between two dates. For this calculation use following code.

To get correct number of days dates should be in yy-mm-dd format. For this use following code.

- (int) daysToDate:(NSDate*) endDate
{
    NSDateFormatter *temp = [[NSDateFormatter alloc] init];
    [temp setDateFormat:@"yyyy-MM-dd"];
    NSDate *stDt = [temp dateFromString:[temp stringFromDate:[NSDate date]]];
    NSDate *endDt =  [temp dateFromString:[temp stringFromDate:endDate]];
    [temp release];
    unsigned int unitFlags = NSDayCalendarUnit;
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:endDt  toDate:stDt options:0];
    int days = [comps day];
   
    [gregorian release];
    return days;
}


Now use the following function where you want to get day difference.

NSString *str =[NSString stringWithFormat:@"%@ 00:00:00",[strdate substringToIndex:10]];
   NSDateFormatter *df = [[NSDateFormatter alloc] init];
   [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
   NSDate *dd = [df dateFromString:str];
   int d = [self daysToDate:dd];

Pass date in yy-mm-dd hh:mm:ss format. Example: 2011-05-28 00:00:00. Date should be in this format in str variable.

Thursday, May 26, 2011

Reverse an array in iPhone SDK

Hello Friends,

We some times need to reverse an array in some cases for such issues there is no ready made function to reverse an array in iPhone SDK.

Solution of this problem can be solved by following function.

- (NSMutableArray *)reverseArray:(NSMutableArray *)arr{
NSUInteger i = 0;
NSUInteger j = [arr count] - 1;
while (i < j) {
[arr exchangeObjectAtIndex:i withObjectAtIndex:j];
i++;
j--;
}
 return arr;
}
Above function will return same array with reverse value.

Setting Image on UIButton

Hello Friends,

Today we will throw a light on very common topic. We often required to set image on UIButton. Images can be set on UIButton with 2 methods. We can set image as button image and button background image.


Generally, We do not set image in button as image inside button because if we set button image then UIButton will enlarge according to the image size. So I prefer you to set Image on background so image will fit to button size.

To set Button title:
[btnImg setTitle:@"ABC" forState: UIControlStateNormal];

To set Background Image in button:
[btnImg setBackgroundImage:image forState: UIControlStateNormal];

To set Button Image:
[btnImg setImage:image forState: UIControlStateNormal];

Have a nice day..!!!

Wednesday, May 25, 2011

Rotate UI Objects in iPhone SDK

Hello Friends,

Today we will take a look for rotating UI object in iPhone SDK. Generally we dot need such kind of stuff in our application. But in some application  this issue can be headache. As such issues should be in developer mind, so work done simple.

To Rotate Button:
button.transform=CGAffineTransformMakeRotation(0.25);

To Rotate Label:
label.transform=CGAffineTransformMakeRotation(0.25);

Have a nice day..!!!

Sunday, May 22, 2011

Search Bar with Clear Background and its Properties

Hello friends,

Today we will go further with the Search Bar's clear back ground and will look at its property set with programmatically.

Follow the following steps:
UISearchBar* mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,160,320,40)];
    mySearchBar.showsCancelButton = NO;
    mySearchBar.userInteractionEnabled = YES;
    mySearchBar.backgroundColor = [UIColor clearColor];
    mySearchBar.tintColor = [UIColor whiteColor];
    mySearchBar.showsScopeBar = NO;
    [self.view addSubview:mySearchBar];
   
    for (UIView *subview in mySearchBar.subviews)
    {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [subview removeFromSuperview];
            break;
        }
    } 

Have a Nice Day.. :-)

Generating Random Numbers in the Given Range

Hello Friends,

Now we will look towards some calculations. In some applications or most of in game development we need to use random number to perform some operations. For Random number generation follow the following steps.

In the header file before interface starts define the following variables.

// GameViewController.h
#define RANDOM_SEED() srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF))
#define RANDOM_NUM() (random())

@interface GameViewController : UIViewController
...

In the GameViewController.m file include the following file.
#include<mach/mach_time.h>

@implementation GameViewController

-(int)getRandomNumber
{
RANDOM_SEED();
int randomSelect=RANDOM_NUM()%([yourArray count]-1); // picks a random number from range 0 to count
return randomSelect;
}

Enjoy.. :-)

Saturday, May 21, 2011

Store Images in local database in iPhone SDK

Hello friends,

Generally, we store images for the application in database using blob in sqlite. But this is not efficient method for storing images. When we store image using blob in sqlite, it basically store in binary data. This takes longer time for loading and storing images. When we have to deal with large and large number of images in application then we should go for the following technique.

Following method stores images in local database:

Formally we write database methods in AppDelegate implementation file. Add the following code in your application file.

-(int)StoreImageLocally:(NSString *)FileName1 :(UIImage *)Image
{
//UIImage *IM;
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: FileName1];
[UIImagePNGRepresentation(Image) writeToFile: filePath atomically:YES];
return 0;
}

Above function will be called by following way to call this function in App Delegate class. Above function store image in iPhone's local database with png format.

[self StoreImageLocally:imageName:Image];

Now to retrieve image from local database, use the following method.
-(UIImage *)GetImage:(NSString *)FileName1
{
if(!IM)
[IM release];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: FileName1];
IM=[[UIImage alloc] initWithContentsOfFile:filePath];
return IM;
}


To use the above function call with following method.

UIImage*  imgphoto=[self GetImage:imageName];

Enjoy..:-)

Friday, May 20, 2011

Customize the color and size of the page control

Hello Friends,

Today we will go for the customize page control. Page control is the functionality is used with scrolling photos. Apple has given UIPageControl for the paging implementation. But that is not customizable in delegate method. It does not contain property variables for the variations. Every time it does not fit in the project. As the project sometimes contain white color background, at that time page control does not appear on the view.

For making customize page control follow the following steps.

To use below code in the your project. Put following code in you project.
 
CGRect f = CGRectMake(0, 0, 320, 20); 
PageControl *pageControl = [[[PageControl alloc] initWithFrame:f] autorelease];
pageControl.numberOfPages = 10;
pageControl.currentPage = 5;
pageControl.delegate = self;
[self addSubview:pageControl];

Now Add the following files in your project.

Header File:
Import


//  Created by Morten Heiberg  on November 1, 2010.
//

@protocol PageControlDelegate;

@interface PageControl : UIView 
{
@private
    NSInteger _currentPage;
    NSInteger _numberOfPages;
    UIColor *dotColorCurrentPage;
    UIColor *dotColorOtherPage;
    NSObject *delegate;
}

// Set these to control the PageControl.
@property (nonatomic) NSInteger currentPage;
@property (nonatomic) NSInteger numberOfPages;

// Customize these as well as the backgroundColor property.
@property (nonatomic, retain) UIColor *dotColorCurrentPage;
@property (nonatomic, retain) UIColor *dotColorOtherPage;

// Optional delegate for callbacks when user taps a page dot.
@property (nonatomic, assign) NSObject *delegate;

@end

@protocol PageControlDelegate
@optional
- (void)pageControlPageDidChange:(PageControl *)pageControl;
@end

Implementation file:

//
//  PageControl.m
//
//  Replacement for UIPageControl because that one only supports white dots.
//
//  Created by Morten Heiberg  on November 1, 2010.
//

#import "PageControl.h"

// Tweak these or make them dynamic.
#define kDotDiameter 7.0
#define kDotSpacer 7.0

@implementation PageControl

@synthesize dotColorCurrentPage;
@synthesize dotColorOtherPage;
@synthesize delegate;

- (NSInteger)currentPage
{
    return _currentPage;
}

- (void)setCurrentPage:(NSInteger)page
{
    _currentPage = MIN(MAX(0, page), _numberOfPages-1);
    [self setNeedsDisplay];
}

- (NSInteger)numberOfPages
{
    return _numberOfPages;
}

- (void)setNumberOfPages:(NSInteger)pages
{
    _numberOfPages = MAX(0, pages);
    _currentPage = MIN(MAX(0, _currentPage), _numberOfPages-1);
    [self setNeedsDisplay];
}

- (id)initWithFrame:(CGRect)frame 
{
    if ((self = [super initWithFrame:frame])) 
    {
        // Default colors.
        self.backgroundColor = [UIColor clearColor];
        self.dotColorCurrentPage = [UIColor blackColor];
        self.dotColorOtherPage = [UIColor lightGrayColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();   
    CGContextSetAllowsAntialiasing(context, true);

    CGRect currentBounds = self.bounds;
    CGFloat dotsWidth = self.numberOfPages*kDotDiameter + MAX(0, self.numberOfPages-1)*kDotSpacer;
    CGFloat x = CGRectGetMidX(currentBounds)-dotsWidth/2;
    CGFloat y = CGRectGetMidY(currentBounds)-kDotDiameter/2;
    for (int i=0; i<_numberOfPages; i++)
    {
        CGRect circleRect = CGRectMake(x, y, kDotDiameter, kDotDiameter);
        if (i == _currentPage)
        {
            CGContextSetFillColorWithColor(context, self.dotColorCurrentPage.CGColor);
        }
        else
        {
            CGContextSetFillColorWithColor(context, self.dotColorOtherPage.CGColor);
        }
        CGContextFillEllipseInRect(context, circleRect);
        x += kDotDiameter + kDotSpacer;
    }
}

- (void)dealloc 
{
    [dotColorCurrentPage release];
    [dotColorOtherPage release];
    [super dealloc];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!self.delegate) return;

    CGPoint touchPoint = [[[event touchesForView:self] anyObject] locationInView:self];

    CGFloat dotSpanX = self.numberOfPages*(kDotDiameter + kDotSpacer);
    CGFloat dotSpanY = kDotDiameter + kDotSpacer;

    CGRect currentBounds = self.bounds;
    CGFloat x = touchPoint.x + dotSpanX/2 - CGRectGetMidX(currentBounds);
    CGFloat y = touchPoint.y + dotSpanY/2 - CGRectGetMidY(currentBounds);

    if ((x<0) || (x>dotSpanX) || (y<0) || (y>dotSpanY)) return;

    self.currentPage = floor(x/(kDotDiameter+kDotSpacer));
    if ([self.delegate respondsToSelector:@selector(pageControlPageDidChange:)])
    {
        [self.delegate pageControlPageDidChange:self];
    }
}

@end


Enjoy... :-)


Saturday, May 14, 2011

Graph and Calendar using Tapku library

Hello friends,

Lets talk about implementing calendars and graphs and many more impressive features in your application using Tapku library. Tapku library is very well structured with all modern functionality.

Tapku library contains Cover flow, Calendars, Loading animations, Custom table cells, Line Graph, HUDs. Main feature of this library is that it is designed for iPhone and iPad both.

Tapku library is open source. Any one can integrate it with their application. Just have a look at this library and integrate bundle in your application. This library can be downloaded from here.

Following screens and functions of tapku library can be implemented with your applications.




Thursday, May 12, 2011

Push Notification in iPhone SDK

Hello Friends,

Now lets look at push notification functionality in iPhone SDK. Push notification is very attractive feature of iPhone SDK.

  • For implementing push notification we have to register device with the server. We have to write code for this functionality in AppDelegate method of application. We will write code in didFinishedLaunching method.

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];


  • Following code will get called when application will launch. Following method will be called only one time at starting of application.

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken 
{ self.deviceToken = [[[devToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" " withString:@""];

//In below methods, deviceToken pass to register device on Web service that send push notification.
[self saveToUserDefaults:self.deviceToken];

//NSLog(@"%@",self.deviceToken);

} 


  • Now we have to write function that will catch the response which will be sent by server for push notification. And we will add some functionality in response. For this, enter following code in App Delegate.

//this method is call when applcation is running and notification is come.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{

// Do whatever when application receive notification that will written in this method.

UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"Notification" message:@"alert" delegate:self cancelButtonTitle:@"Update" otherButtonTitles:nil];
[alertview show];
[alertview release];
}

Monday, May 9, 2011

Put background image in navigation bar in iphone sdk

Hello friends,

Today I am going to write one useful method for making custom navigation bar. We will change the color of navigation bar by inserting color image in navigation bar. We can do this by making new class for the custom navigation controller. Make following two files in any application.
  • Create Objective-C class file. Do not create xib. In the header file insert following code. Import the <UIKit/UIKit.h> file.
@interface UINavigationBar
    - (void) setBackgroundImage:(UIImage*)image;
    - (void) clearBackgroundImage;
@end

  • Then in implementation file write the following code.
@implementation UINavigationBar (CustomImage)

- (void) setBackgroundImage:(UIImage*)image {
    if (image == NULL) return;
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, 320, 44);
    [self insertSubview:imageView atIndex:0];
    [imageView release];
}

- (void) clearBackgroundImage {
    NSArray *subviews = [self subviews];
    for (int i=0; i<[subviews count]; i++) {
        if ([[subviews objectAtIndex:i]  isMemberOfClass:[UIImageView class]]) {
        [[subviews objectAtIndex:i] removeFromSuperview];
    }
   }    
}

@end
  • Now write the following code in the application where you want the custom navigation bar. Generally we write such code in viewWillAppear method.
UINavigationBar *navBar = self.navigationController.navigationBar;
UIImage *image = [UIImage imageNamed:@"NavigaionBarBackground.png"];
[navBar clearBackgroundImage]; 
[navBar setBackgroundImage:image];

Sunday, May 8, 2011

Table in iPhone sdk

Hello Friends,

Today we will learn Table implementation methods in iOS SDK. Table is very important part of the iPhone development. 90% of the applications are made with use of table. Table view in iPhone SDK provides very flexibility in designing and coding. All the contents can be scrollable with table view. Contact application in iPhone is built with the use of table view only. Table view implementation is very easy and its data source and delegate methods enhance its flexibility. So, now here we will learn some data source and delegate methods for the table view.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}


The main method of Data Source is to fill the data in the table. Above methods create table and following methods will fill the data in table.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}


To set the actions when tables rows are pressed we have to create Delegate methods for that. Delegate methods will create an action when user will tap the Cell or Row of the table. We will learn one main method of delegate here. Following method creates action for our table.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

// Generally here we put some action code like when user taps cell, new view or nib is pushed from the current nib.

Detailview *detailViewController = [[Detailview alloc] initWithNibName:@"Detailview" bundle:nil];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];

}


Above code will push new xib for the detail view. Alert view is also implemented in this method.

Wednesday, May 4, 2011

Code for Sending SMS from iPhone Application

Hello Friends,

Today we will learn to send sms from your iPhone application. As always Apple has provided ready to use frame work for sending sms from your application. Writing a code for sending sms as easy as sending a sms from iPhone. To implement this functionality let's start quick tutorial.

  • Add frame work in your application named "MessageUI.framework".
  • Import<UIKit/UIKit.h> , <MessageUI/MessageUI.h> ,  <MessageUI/MFMailComposeViewController.h> files in header file and write the following code in header file (.h file).

@interface MessageComposerViewController : UIViewController < MFMessageComposeViewControllerDelegate> {
      
       IBOutlet UILabel *feedbackMsg;
}

@property (nonatomic, retain) IBOutlet UILabel *feedbackMsg;

-(IBAction)showSMSPicker:(id)sender;
-(void)displaySMSComposerSheet;

@end

  • Add the following code in implementation file (.m file).
Following code will check device configuration and will throw error if it is not configured properly.

-(IBAction)showSMSPicker:(id)sender {
//     The MFMessageComposeViewController class is only available in iPhone OS 4.0 or later.
//     So, we must verify the existence of the above class and log an error message for devices
//       running earlier versions of the iPhone OS. Set feedbackMsg if device doesn't support
//       MFMessageComposeViewController API.
       Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
      
       if (messageClass != nil) {                          
          // Check whether the current device is configured for sending SMS messages
          if ([messageClass canSendText]) {
                   [self displaySMSComposerSheet];
          }
          else {         
                   feedbackMsg.hidden = NO;
                   feedbackMsg.text = @"Device not configured to send SMS.";

          }
       }
       else {
          feedbackMsg.hidden = NO;
          feedbackMsg.text = @"Device not configured to send SMS.";
       }
}

       //IF device is configure successfully then below code will run.

          // Displays an SMS composition interface inside the application.
-(void)displaySMSComposerSheet
{
       MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
       picker.messageComposeDelegate = self;
      
       [self presentModalViewController:picker animated:YES];
       [picker release];
}


// Dismisses the message composition interface when users tap Cancel or Send. Proceeds to update the
// feedback message field with the result of the operation.

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                     didFinishWithResult:(MessageComposeResult)result {
      
       feedbackMsg.hidden = NO;
       // Notifies users about errors associated with the interface
       switch (result)
       {
          case MessageComposeResultCancelled:
                   feedbackMsg.text = @"Result: SMS sending canceled";
                   break;
          case MessageComposeResultSent:
                   feedbackMsg.text = @"Result: SMS sent";
                   break;
          case MessageComposeResultFailed:
                   feedbackMsg.text = @"Result: SMS sending failed";
                   break;
          default:
                   feedbackMsg.text = @"Result: SMS not sent";
                   break;
       }
       [self dismissModalViewControllerAnimated:YES];
}







Sunday, May 1, 2011

Twitter Connections and Post in iPhone SDK

Hello Friends,

Now we will start learning integration of twitter with our application. First you have to register your application with twitter, then they will give you Consumer Key and Consumer Secret. These both keys are necessary for twitter integration.


  • Download yajl library from the internet. Yajl
  • Add the following code to your project. I recommend you to use oAuth+MGTwitterEngine for the twitter integration. 
  • Insert following code for the header file to define constants.
#define kTwitterConsumerKey @"VcpHtgcXcLYFRAkZssZo9R"
#define kTwitterConsumerSecret @"JCHJtoQ5Ihjq7sxbvRkHLuAZBxZc4LEn66Fldcx5tXZ"
#define kCachedXAuthAccessTokenStringKey @"cachedXAuthAccessTokenKey"


  • Call this method on twitter button pressed event.
[self xAuthAccessTokenRequestButtonTouchUpInside];

  • Add the following methods to your class file. Following methods are twitter methods.
#pragma mark --------------Twitter Methods------------------
#pragma mark -
#pragma mark Actions

- (void)xAuthAccessTokenRequestButtonTouchUpInside
{
NSString *username = twitterUserName;// self.usernameTextField.text;
NSString *password = twitterPassword;//self.passwordTextField.text;

NSLog(@"About to request an xAuth token exchange for username: ]%@[ password: ]%@[.",
username, password);

[self.twitterEngine exchangeAccessTokenForUsername:username password:password];
}

- (void)sendTestTweetButtonTouchUpInside
{
NSString *tweetText = [NSString stringWithFormat:@"Welcome to your First Twitter Application"];
NSLog(@"About to send test tweet: \"%@\"", tweetText);
[self.twitterEngine sendUpdate:tweetText];
}

#pragma mark -
#pragma mark XAuthTwitterEngineDelegate methods

- (void) storeCachedTwitterXAuthAccessTokenString: (NSString *)tokenString forUsername:(NSString *)username
{
//
// Note: do not use NSUserDefaults to store this in a production environment. 
// ===== Use the keychain instead. Check out SFHFKeychainUtils if you want 
// an easy to use library. (http://github.com/ldandersen/scifihifi-iphone) 
//
NSLog(@"Access token string returned: %@", tokenString);

[[NSUserDefaults standardUserDefaults] setObject:tokenString forKey:kCachedXAuthAccessTokenStringKey];
UIAlertViewQuick(@"Authentication Success", @"Your username and password have successfully authenticated.", @"OK");
[[UIApplication sharedApplication] endIgnoringInteractionEvents];

// Enable the send tweet button.
//self.sendTweetButton.enabled = YES;
}

- (NSString *) cachedTwitterXAuthAccessTokenStringForUsername: (NSString *)username;
{
NSString *accessTokenString = [[NSUserDefaults standardUserDefaults] objectForKey:kCachedXAuthAccessTokenStringKey];

NSLog(@"About to return access token string: %@", accessTokenString);

return accessTokenString;
}


- (void) twitterXAuthConnectionDidFailWithError: (NSError *)error;
{
NSLog(@"Error: %@", error);

UIAlertViewQuick(@"Authentication error", @"Please check your username and password and try again.", @"OK");
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}


#pragma mark -
#pragma mark MGTwitterEngineDelegate methods

- (void)requestSucceeded:(NSString *)connectionIdentifier
{
NSLog(@"Twitter request succeeded: %@", connectionIdentifier);

UIAlertViewQuick(@"Tweet sent!", @"The tweet was successfully sent. Everything works!", @"OK");
}

- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error
{
NSLog(@"Twitter request failed: %@ with error:%@", connectionIdentifier, error);

if ([[error domain] isEqualToString: @"HTTP"])
{
switch ([error code]) {

case 401:
{
// Unauthorized. The user's credentials failed to verify.
UIAlertViewQuick(@"Oops!", @"Your username and password could not be verified. Double check that you entered them correctly and try again.", @"OK"); 
break; 
}

case 502:
{
// Bad gateway: twitter is down or being upgraded.
UIAlertViewQuick(@"Fail whale!", @"Looks like Twitter is down or being updated. Please wait a few seconds and try again.", @"OK"); 
break; 
}

case 503:
{
// Service unavailable
UIAlertViewQuick(@"Hold your taps!", @"Looks like Twitter is overloaded. Please wait a few seconds and try again.", @"OK"); 
break; 
}

default:
{
NSString *errorMessage = [[NSString alloc] initWithFormat: @"%d %@", [error code], [error localizedDescription]];
UIAlertViewQuick(@"Twitter error!", errorMessage, @"OK"); 
[errorMessage release];
break; 
}
}

}
else 
{
switch ([error code]) {

case -1009:
{
UIAlertViewQuick(@"You're offline!", @"Sorry, it looks like you lost your Internet connection. Please reconnect and try again.", @"OK"); 
break; 
}

case -1200:
{
UIAlertViewQuick(@"Secure connection failed", @"I couldn't connect to Twitter. This is most likely a temporary issue, please try again.", @"OK"); 
break; 
}

default:
{ 
NSString *errorMessage = [[NSString alloc] initWithFormat:@"%@ xx %d: %@", [error domain], [error code], [error localizedDescription]];
UIAlertViewQuick(@"Network Error!", errorMessage , @"OK");
[errorMessage release];
}
}
}

}

  • You can download source code for the Twitter Integration from gitHub also. This contains sample application also. Download source code here.

UIWebView Tutorial

Hello Friends,

Now we will use excellent feature of iOS SDK. In iOS apple has provided us ready made library for the web interaction. It is so finely designed that all the desired features are included in library. We can easily make browser application with this feature.

Now we will write a code to open www.apple.com website in application. We will start this work by creating View Based Application.

  • Create View Based Application and Give a name to it like WebView.
  • Open WebViewViewController.xib file in interface builder.
  • Drag a Web View from library to main View.
  • Now open WebViewController.h file and write a following code. 
@interface WebViewController : UIViewController {
IBOutlet UIWebView *webView;
}

@property (nonatomic, retain) UIWebView *webView;

@end
  • Now Save the header file and open interface builder again for connecting outlet again to the UIWebView which we have added just before to the main view.
  • After Connecting outlet to the UIWebView Controller, We can use that WebView in implementation file.
  • Do not forget to synthesize webView object in Implementation file. @synthesize method set the setter method for the webView object.
  • Now open WebViewController.m file and add the following code. 
- (void)viewDidLoad {
NSString *urlAddress = @”http://www.apple.com”;

//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];

//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}

  •  NSURL class is used to create an object which will hold the URL information.
  •  NSURLRequest is used to create a request to the URL.
  •  LoadRequest  method of UIWebView is used to load the request in the UIWebView.
Now Build and Run Program you should be able to see www.apple.com page. :-)

    Use of Image Picker in iPhone SDK


    Hello Friends now we will start to learn about image handling in iPhone. Apple has provided us most of the stuff ready for the use.  UIImagePicker is best example of that. We just have to invoke the function for the picking image from the iphone or to take image from camera.  Any novice developer can use this library easily.
    Methods of picking images from iPhone are deprecated. This method is available from iOS 3.0.
     Let’s start this stuff with View based Application.
    • Create View Based Application and Give a name to it.
    • Create IBOutlet and IBAction in ImageViewController.h. For that write following code  ImageViewController.h.
    @interface ImageViewController : UIViewController < UIImagePickerControllerDelegate,UINavigationControllerDelegate > 
    {
                   UIImageView *imageView;
                   UIButton *selectPhotobtn;
                   UIButton *takePhotobtn;
    }
    @property (nonatomic, retain) IBOutlet UIImageView *imageView;
    @property (nonatomic, retain) IBOutlet UIButton *selectPhotobtn;
    @property (nonatomic, retain) IBOutlet UIButton *takePhotobtn;
    
    -(IBAction) getPhoto:(id) sender;
    @end
    
    

            
    UIImagePickerControlDelegate and the UINavigationControllerDelegate are needed for properly interface with the image picker. 
    •  Create interface by opening ImageViewController.xib in the interface builder. 
    Ø  Drag a UIImageView on the main view.
    Ø  Set the Mode of the UIImageView to Aspect Fit in the Attribute inspector.
    Ø  Drag a UIButton on to the view and title it Select Photo.
    Ø  Drag another UIButton on to the view and title it Take Photo.

    • Connect the IBoutlets and IBAction

    Ø  Connect selectPhotobtn to the UIButton titled Select Photo.
    Ø  Connect takePhotobtn to the UIButton titled Take Photo.
    Ø  Connect the imageView to the UIImageView.
    Ø  Connect the Touch Up Inside Callback on each of the buttons to the getPhoto method.

    •   Now we have to implement the code for the getPhoto method.

    @synthesize imageView,selectPhotobtn,takePhotobtn;
     
    -(IBAction) getPhoto:(id) sender {
       UIImagePickerController * picker = [[UIImagePickerController alloc] init];
       picker.delegate = self;
     
       if((UIButton *) sender == selectPhotobtn) 
       {
               picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
       } 
       else
       {
              picker.sourceType = UIImagePickerControllerSourceTypeCamera;
       }
      [self presentModalViewController:picker animated:YES];
    }
    

    
    
    • Once a photo is selected, the ImagePicker will callback to a method in our class called didFinishPickingMediaWithInfo.  This is a delegate method. Add the following code to ImageViewController.m file.

    - (void)imagePickerController:(UIImagePickerController *)picker 
    didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
     [picker dismissModalViewControllerAnimated:YES];
     imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    }
    

    
    
    In iOS everything is so finely designed that one can understand function use from its name. Only this stuff can create very good demo application in iPhone.

    Saturday, April 30, 2011

    Use Three20 and UICatalog for the sample Code in iPhone SDK

    Hello Friends,

    I want to share one thing with you about sample code for the various functions. Most of us, try to find some basic code for the starting development of any kind of projects. So I recommend you to go with Apple's Development Guide. Friends, you can also register with apple on www.developer.apple.com without any cost. By registering your self with Apple you can download sample code of various functions of iOS SDK.

    Three20 is a best example of use of various functions of iOS sdk. This can be found on GitHub. You can download such code and use it on different programs.

    It can be found on this link: Three20 Catalog

    You can also download UICatalog from Apple's Development site: UI Catalog

    For example you can find various transitions methods that can be used for a slideshow in this examples.

      

    Objective-C before you step into iPhone Development

    Hello Friends,

    Before you step into vast field on iOS development. You should be familiar with fundamentals of objective-C as I stated in my earlier post. Whole iOS is written in objective-C. If you are master in objective-C then you can directly start iPhone developing right away. If you are entering in iWorld first time then you should have cleared fundamentals of objective-C.

    For the best practice of objective-C concepts, I recommend you following book for the depth and clear understanding.

    You can buy this book from following link.
    Objective C E-book

    Or you can read whole book here also.



    iPhone Programming Book and Guide

    Hello Friends,

    On the basis of my experience and knowledge, I want to share one E-Book for learning iPhone development which must be read by everyone who is entering in iOS world. This book is strongly recommended by me for the smooth learning.

    Apress Beginning IPhone 4 Development



    This is best book that I recommend to you for beginning development. All the programs are very well prepared and all chapters and languages are very coherent. If any body has any doubt regarding any program in this book, please post your questions here.

    All the best. :-)  

    Introduction of Navigation based Application in iPhone

    In iPhone programming, navigation based application helps us to make application which contains many screens those should me connected to each other and they should be easily navigated to other screens. iOS sdk provides us Navigation Controller for make it easy.


    Best primary example of navigation based application is Contact Application in iPhone. Such application can be started to build by selecting Navigation Based Application in Xcode.


    When you create navigation based applications, you will find many files made by Xcode them self. Each file has its own importance. 


     You Should find following files after creating navigation application.


    • CoreGraphics.framework, Foundation.framwork, UIKit.framework - These are the basic libraries which are provided by apple. These library contains many functions as other languages.
    • HelloWorld.app -  This is an Application which will be installed in iPhone
    • Hello_World_Prefix.pch -   It contains some code to include the data inside the frameworks.
    • Hello_WorldAppDelegate.h -This is a header file that contains all of our definitions for variables.  It is very similar to a header file in other languages.
    • Hello_WorldAppDelegate.m -   This is first execution file which will be executed when program runs. The main .m file calls this object.
    • Info.plist - This contains various meta information about our program.  
    • main.m - Like most programming language, this file contains our main function. Execution begins from here.  The main function basically instantiates our object and starts the program.  We should not need to edit this file.
    • MainWindow.xib - This contains the visual information of  main window.  If we double click on it, it will open in a program called “Interface Builder”.
    • RootViewController.h, RootViewController.m - These are files for a view controller that gets added to our main window.  
    • RootViewController.xib - This is a display file which can be edited in interface builder.
    We will write our main code of Hello World in Root View Controller.m file.
    Open that file and write following code.


    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
    }


    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
    }


    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *Identifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:Identifier] autorelease];
    }
    [cell setText:@"Hello World"];
    // Set up the cell
    return cell;
    }


     - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic
    }


    Save and Compile your program. Run the program in simulator. 

    You should get following output.


    Welcome to My Blog, We are starting with prerequisites for iPhone Development.


    Hello Friends,
    Good to see you on this blog. This is my first post on this iPhone Development blog.  Here now we are going to start iPhone development.
    For the iPhone development you need following software.
    1.  iMac, Macbook or Macbook Pro
    2. Xcode with iOS sdk.
    3. SQLite Database.
    4. iPhone for the testing purpose.


    For the iPhone development you need basic knowledge of the following skills.
    1. You must have strong knowledge of Object Oriented Programming.
    2. You must have knowledge of SQL. [At least you should know how to deal with database. You should  know how to throw query on database.]
    3. You should clear basics of objective-c. [You should be familiar with programming style of objective-c as iOS is written in objective-c.]


    Now, we are going to write First program in Xcode.  We will start practicing with “Hello World!” program.