Powered By Blogger

Friday, December 7, 2012

how to make custom segmented control?

Hi,
Many of you want to make custom controls in their own projects but sometime they need some guidance or the way to customize those controls. So, here is the way for everyone who wants to make his/her own custom segmented control in iPhone, iPad projects. Please follow the below steps :

Step 1 : Import these two files in your projects . ("CustomsegmentControl.h","CustomsegmentControl.m")

#import <UIKit/UIKit.h>

@interface CustomSegmentControl : UISegmentedControl
{
    UIColor *unselectedColor,*selectedColor;
}
@property (nonatomic,retain) UIColor *unselectedColor,*selectedColor;
-(id)initWithItems:(NSArray *)items unselectedColor:(UIColor*)unselectedColor selectedColor:(UIColor*)selectedColor;
@end


#import "CustomSegmentControl.h"

@interface CustomSegmentControl(private)
-(void)setupInitialMode;
-(void)switchHighlightColors;
@end

@implementation CustomSegmentControl

@synthesize unselectedColor,selectedColor;

-(id)initWithItems:(NSArray *)items unselectedColor:(UIColor*)unselectedColor selectedColor:(UIColor*)selectedColor {
    if (self = [super initWithItems:items])
    {
        // Initialization code
        self.unselectedColor = unselectedColor;
        self.selectedColor = selectedColor;
        [self setInitialMode];
        [self setSelectedSegmentIndex:0];
    }
    return self;
}
- (void)awakeFromNib
{
    self.unselectedColor = [UIColor colorWithWhite:0.7 alpha:1];
    self.selectedColor = self.tintColor;
    [self setInitialMode];
   
    [self setSelectedSegmentIndex:0];
}

-(void)setupInitialMode
{
    [self setBackgroundColor:[UIColor clearColor]];
    [self setSegmentedControlStyle:UISegmentedControlStyleBar];
   
    for( int i = 0; i < [self.subviews count]; i++ )
    {
        [[self.subviews objectAtIndex:i] setTintColor:nil];
        [[self.subviews objectAtIndex:i] setTintColor:unselectedColor];
    }
    [self addTarget:self action:@selector(switchHighlightColors) forControlEvents:UIControlEventValueChanged];
}


-(void)switchHighlightColors
{
    for (id view in self.subviews) {
        if ([view isSelected]) [view setTintColor:selectedColor];
        else [view setTintColor:unselectedColor];
    }
}

- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex
{
    [super setSelectedSegmentIndex:selectedSegmentIndex];
    [self switchHighlightColors];
}
@end

Step 2 :  Now make your new custom segment control in the class file wherever you want to use that custom control. 

For example : CustomSegmentControl *obj_customsegment;

obj_customsegment = [[CustomSegmentControl alloc]initWithItems:[NSArray arrayWithObjects:@"One",@"Two",nil] unselectedColor:[UIColor blackColor] selectedColor:[UIColor blueColor]];


Now, you can easily use above custom segment control object in your project.

Regards,
Nilesh Prajapati

Tuesday, November 27, 2012

how to change the selected segment button color ?

Hi all,
Please use the below code if you want to change the color of UISegmentedControl's component after the selection of that rather showing the default color.

For example : 

UISegmentedControl *segmentedControl; // You can use your own segmented control rather using this one...

UIColor *selectedColor = [UIColor colorWithRed: 0.0f/255.0 green:0.0f/255.0 blue:255.0f/255.0 alpha:1.0];
         UIColor *deselectedColor = [UIColor colorWithRed: 0.0f/255.0 green: 0.0f/255.0 blue: 255.0/255.0 alpha:0.2];

for (id subview in [segmentedControl subviews]) {
    if ([subview isSelected])
       [subview setTintColor:selectedColor];
    else
       [subview setTintColor:deselectedColor];
}


Thanks,
Nilesh Prajapati

how to add gradient effect to button in iphone?

Hi friends,
If anyone, of you, want to add gradient effect to custom button then here is the way to add that effect.

Example :

        // Add Border to button
        CALayer *layer = btnCalender.layer;
        layer.cornerRadius = 5.0f;
        layer.masksToBounds = YES;
        layer.borderWidth = 1.0f;
        layer.borderColor = [UIColor colorWithWhite:0.3f alpha:0.2f].CGColor;
       
        // Add Shine to button
        CAGradientLayer *Layer = [CAGradientLayer layer];
        Layer = layer.bounds;
        Layer.colors = [NSArray arrayWithObjects:
                             (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                             (id)[UIColor colorWithWhite:1.0f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:0.75f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                             nil];
        Layer.locations = [NSArray arrayWithObjects:
                                [NSNumber numberWithFloat:0.0f],
                                [NSNumber numberWithFloat:0.2f],
                                [NSNumber numberWithFloat:0.3f],
                                [NSNumber numberWithFloat:0.0f],
                                [NSNumber numberWithFloat:1.0f],
                                nil];
        [layer addSublayer: Layer];

Regards, 
Nilesh Prajapati

Saturday, November 24, 2012

how to use NSDateFormatter for different format?

 Hi,
Using the below category for NSDate, you can use below functions to get various date format string or date.

 #import <Foundation/Foundation.h>

@interface NSDate(TCUtils)

- (NSDate *)TC_dateByAddingCalendarUnits:(NSCalendarUnit)calendarUnit amount:(NSInteger)amount;
- (NSString*)TC_dateindisplayformat:(NSString*) format;
- (NSString*)TC_datewithTformat:(NSString*)dt format:(NSString*) format;
- (NSString*)TC_dateformat:(NSString*)dt format:(NSString*) format;
- (NSDate*)TC_stringformat:(NSString*)dt format:(NSString*) format;
- (NSString*)TC_date24format:(NSString*)dt format:(NSString*) format;
- (NSDate*)TC_datewithTformat:(NSString*)dt;
- (BOOL)isSameDay:(NSDate*)anotherDate;
- (NSDate *) todayDateWithoutTime;
@end



#import "NSDate+TCUtils.h"

@implementation NSDate (TCUtils)


- (NSDate *)TC_dateByAddingCalendarUnits:(NSCalendarUnit)calendarUnit amount:(NSInteger)amount {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *newDate;
   
    switch (calendarUnit) {
        case NSSecondCalendarUnit:
            [components setSecond:amount];
            break;
        case NSMinuteCalendarUnit:
            [components setMinute:amount];
            break;
        case NSHourCalendarUnit:
            [components setHour:amount];
            break;
        case NSDayCalendarUnit:
            [components setDay:amount];
            break;
        case NSWeekCalendarUnit:
            [components setWeek:amount];
            break;
        case NSMonthCalendarUnit:
            [components setMonth:amount];
            break;
        case NSYearCalendarUnit:
            [components setYear:amount];
            break;
        default:
            ////NSLog(@"addCalendar does not support that calendarUnit!");
            break;
    }
   
    newDate = [gregorian dateByAddingComponents:components toDate:self options:0];
    [components release];
    [gregorian release];
    return newDate;
}

- (NSString*)TC_dateindisplayformat:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:format];
    return [df stringFromDate:self];   
}

- (NSString*)TC_datewithTformat:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSArray* a=[dt componentsSeparatedByString:@"T"];
    NSDate* tdt;
    if([a count]>0){
        tdt=[df dateFromString:[a objectAtIndex:0]];
    }
    else{
        tdt=[NSDate date];
    }
    [df setDateFormat:format];
   
    return [df stringFromDate:tdt];
}

- (NSString*)TC_dateformat:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate* tdt=[df dateFromString:dt];
    [df setDateFormat:format];
   
    return [df stringFromDate:tdt];
}

- (NSDate*)TC_stringformat:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:format];

    return [df dateFromString:dt];
}

- (NSDate*)TC_datewithTformat:(NSString*)dt
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
    [df setLocale:locale];
    dt=[dt stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [df dateFromString:dt];
}

- (NSString*)TC_date24format:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd hh:mm a"];
    NSDate* tdt=[df dateFromString:dt];
    [df setDateFormat:format];
   
    return [df stringFromDate:tdt];
}

- (NSDate *) todayDateWithoutTime
{
    NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
      [df setTimeZone:[NSTimeZone  defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd"];

    NSString *todayDateS = [df stringFromDate:[NSDate date]];
    NSDate *todayDate = [df dateFromString:todayDateS];
    return todayDate;
}



- (BOOL)isSameDay:(NSDate*)anotherDate{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components1 = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self];
    NSDateComponents* components2 = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:anotherDate];
    return ([components1 year] == [components2 year] && [components1 month] == [components2 month] && [components1 day] == [components2 day]);
}

@end

Friday, November 23, 2012

how to add video url in webview as thumbnail in iphone ?

Hi friends,
This is the example for showing Video thumbnail icon in webview just as it appears in normal/youtube video list.

-(void)viewDidLoad
{
    UIWebView *webViewVideo = [[UIWebView alloc] initWithFrame:CGRectMake(0, (1024-500)/2, 768, 500)];
    [webViewVideo setBackgroundColor:[UIColor redColor]];
   
    UIButton* b=(UIButton*)sender;
   
    NSString* urlString=[array_Youtube objectAtIndex:b.tag];
   
    NSString *embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
    background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";
    NSString *html;
    html = [NSString stringWithFormat:embedHTML, urlString, 768.0, 500.0];
       
    [webViewVideo loadHTMLString:html  baseURL:nil];
    //UIView* v=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
    //[v addSubview:webViewVideo];
    //v.backgroundColor=[UIColor blackColor];
   
    [self.view addSubview:webViewVideo];
    [webViewVideo release];
}

 I hope this will be the useful to everyone of you.

Thanks,
Nilesh Prajapati

Tuesday, October 30, 2012

how to check iPhone volume programmatically?

Hi everyone,
Below is the trick to check the iPhone/iPad/iPod Touch (iOS Device) volume level. Please take a look..

#import <AudioToolbox/AudioToolbox.h>

    Float32 volume;
    UInt32 dataSize = sizeof(Float32);
    AudioSessionGetProperty (
                             kAudioSessionProperty_CurrentHardwareOutputVolume,
                             &dataSize,
                             &volume
                             );
    NSLog(@"Volume Level : %f",volume);
    if (volume <= 0.25)
    {
              NSLog(@"Volume is below %d \%",(volume*100));
    }

Thanks,
Nilesh M. Prajapati

how to create UUID in iPhone?

Hi friends,
Here is the example for creating UUID in your iPhone/iPad/iPod Touch application.

            NSString *deviceUuid = nil;
            CFStringRef cfUuid = CFUUIDCreateString(NULL, CFUUIDCreate(NULL));
            deviceUuid = (NSString *)cfUuid;
            NSLog(@"deviceUuid : %@",deviceUuid);
            CFRelease(cfUuid);

Now , you can use this "deviceUuid" as UUID.

Thanks,
Nilesh M. Prajapati

Saturday, October 20, 2012

how to implement MPMoviePlayerViewController in iPhone?

Hi every one,
Please take a look at MPMoviePlayerController integration for local/live video playing in iPhone/iPad/iPod Touch (iOS 4.0 and later..).

Step 1 : Add "MediaPlayer.framework" into your project resource.
Step 2 :  Import <MediaPlayer/MediaPlayer.h> into your class where you want to use MediaPlayer for playing videos (local/live).
Step 3 : Place below code into the controller class where you want to integrate player.

-(IBAction)btnVideoClicked:(id)sender
{
    @try
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        GetVideos *obj_video = [arrVideos objectAtIndex:[sender tag]];
        MPMoviePlayerViewController *moviePlayerViewController = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:obj_video.VideoPath]];
        [moviePlayerViewController.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
        [moviePlayerViewController.moviePlayer setShouldAutoplay:YES];
        [moviePlayerViewController.moviePlayer setFullscreen:NO animated:YES];
        [moviePlayerViewController setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
        [moviePlayerViewController.moviePlayer setScalingMode:MPMovieScalingModeNone];
        [moviePlayerViewController.moviePlayer setUseApplicationAudioSession:NO];
        // Register to receive a notification when the movie has finished playing. 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(moviePlaybackStateDidChange:) 
                                                     name:MPMoviePlayerPlaybackStateDidChangeNotification 
                                                   object:moviePlayerViewController];
        // Register to receive a notification when the movie has finished playing. 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(moviePlayBackDidFinish:) 
                                                     name:MPMoviePlayerPlaybackDidFinishNotification 
                                                   object:moviePlayerViewController];
        [self presentMoviePlayerViewControllerAnimated:moviePlayerViewController];
        moviePlayerViewController.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
        [moviePlayerViewController release];
        [pool release];
    }
    @catch (NSException *exception) {
        // throws exception
    }
}


#pragma mark -----------------------
#pragma mark MPMoviePlayer Notification Methods


-(void)moviePlaybackStateDidChange:(NSNotification *)notification
{

    MPMoviePlayerViewController *moviePlayerViewController = [notification object]; 

    if (moviePlayerViewController.moviePlayer.loadState == MPMovieLoadStatePlayable &&
        moviePlayerViewController.moviePlayer.playbackState != MPMoviePlaybackStatePlaying)
    {
        [moviePlayerViewController.moviePlayer play];
    }
   
    // Register to receive a notification when the movie has finished playing. 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification 
                                               object:moviePlayerViewController];
    moviePlayerViewController = nil;
}

- (void) moviePlayBackDidFinish:(NSNotification*)notification

    MPMoviePlayerViewController *moviePlayerViewController = [notification object]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:MPMoviePlayerPlaybackDidFinishNotification 
                                                  object:moviePlayerViewController]; 
    [self dismissMoviePlayerViewControllerAnimated];
    moviePlayerViewController = nil;


Thanks ,
Nilesh M. Prajapati

Tuesday, October 16, 2012

How to integrate live audio streaming in iPhone?

Hi everyone,
I think, all of you heard about live audio/video streaming. I'm going to share "Live Audio Streaming" example with you.
Please check this :

Step 1: First of all, you have to download these two files(AudioStreamer.h, AudioStreamer.m) from http://code.google.com/p/audiostreamer-meta/source/browse/trunk/Classes

Step 2: Add necessary frameworks and above two files into your project.

Step 3:
Implement below code to your project file.

@class AudioStreamer;

@interface CallerTuneListViewController : UIViewController
{
    AudioStreamer *streamer;
}

#import "CallerTuneListViewController.h"

#import "AudioStreamer.h"
#import <QuartzCore/CoreAnimation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <CFNetwork/CFNetwork.h>
#import <AudioToolbox/AudioToolbox.h>

@implementation CallerTuneListViewController

#pragma mark ---------------------------------
#pragma mark View LifeCycle

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([streamer isPlaying]) {
        [self destroyStreamer];
    }
}

#pragma mark ---------------------------------
#pragma mark Memory Management

- (void)dealloc
{
    [self destroyStreamer];
    [super dealloc];
}

#pragma mark ---------------------------------
#pragma mark UIButton Actions

-(IBAction)playLiveStream:(id)sender
{
            if (![streamer isPlaying])
                {
                    [self createStreamer:AudioFilePath];
                    [streamer start];
                }
                else
                {
                    [streamer stop];
                }
}


#pragma mark ---------------------------------
#pragma mark AudioStreamer Methods

// Removes the streamer, the UI update timer and the change notification
- (void)destroyStreamer
{
    if (streamer)
    {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:streamer];
      
        [streamer stop];
        [streamer release];
        streamer = nil;
    }
}

// Creates or recreates the AudioStreamer object.
- (void)createStreamer:(NSString *)audioPath
{
    if (streamer)
    {
        return;
    }
  
    [self destroyStreamer];
  
    NSURL *url = [NSURL URLWithString:audioPath];
    streamer = [[AudioStreamer alloc] initWithURL:url];

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(playbackStateChanged:)
     name:ASStatusChangedNotification
     object:streamer];
}

// Invoked when the AudioStreamer
// reports that its playback status has changed.
- (void)playbackStateChanged:(NSNotification *)aNotification
{
    if ([streamer isWaiting])
    {
    }
    else if ([streamer isPlaying])
    {
    }
    else if ([streamer isIdle])
    {
        [self destroyStreamer];
    }
}

I hope this will be useful to all...

Thanks ,
Nilesh M. Prajapati

How to make paging in iPhone?

Hi,
Here is the example of horizontal paging using UIScrollView and its property pagingEnabled.

Look at the below code :

- (void)viewDidLoad
{
    [super viewDidLoad];
    pageCount = 0;
    scrollView.pagingEnabled = YES;
}

#pragma mark ---------------------
#pragma mark User-Defined Methods

-(void)GenerateVideoThumbnail
{
    for (UIView *videoView in self.scrollView.subviews)
    {
        [videoView removeFromSuperview];
        videoView = nil;
    }

    CGFloat X = 12.5,Y = 5.0; // Button X and Y position
    CGFloat Width = 90.0,Height = 90.0;
    CGFloat XDiff = 12.5,YDiff = 5.0;
    NSInteger MaxIconPerRow = 3;  
    NSInteger MaxIconPerPage = 12;

    for (int i=0; i<[arrVideos count]; i++)
    {
        GetVideos *obj_video = [arrVideos objectAtIndex:i];
        UIButton *btnVideo = [UIButton buttonWithType:UIButtonTypeCustom];
        btnVideo.tag = i;
        NSLog(@"frame X: %f, Y: %f",btnVideo.frame.origin.x,btnVideo.frame.origin.y);
        [btnVideo setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:obj_video.Thumnailpath]]] forState:UIControlStateNormal];

        btnVideo.frame = CGRectMake(X, Y, Width, Height);
        [self.scrollView addSubview:btnVideo];
        [btnVideo startLoading];
        btnVideo = nil;
       
        X = X + Width + XDiff;
        if((i+1)%MaxIconPerRow ==0)
        {
            X = (pageCount*320.0) + XDiff;
            Y = Y + Height + YDiff;
        }
        if((i+1)%MaxIconPerPage ==0)
        {
            ++pageCount;
            X = (pageCount*320.0) + XDiff;
            Y = 5.0;
        }
    }
    self.scrollView.contentSize = CGSizeMake((pageCount*self.scrollView.frame.size.width), self.scrollView.frame.size.height);
}

Thursday, October 4, 2012

How to add custom fonts to iPhone application?

Hi,

As of iOS 4.0 and later iOS version came, it has become very easy to add custom fonts to your iPhone/iPad/iPod applications. Here, some steps you have to follow in order to add custom fonts:

    1.    Add your custom font files into your project using XCode as a resource
    2.    Add a key to your info.plist file called UIAppFonts.
    3.    Make this key an array
    4.    For each font you have, enter the full name of your font file (including the extension) as items
           to the UIAppFonts array.
    5.    Save info.plist
    6.    Now in your application you can simply call
           [UIFont  fontWithName:@"CustomFontName" size:FontSize]
           to get the custom font to use with your UILabels and UITextViews, etc…

It’s very simple to integrate!

Monday, October 1, 2012

Mask animation in iPhone

Hi,
Here is the sample code for "Mask Animation" in Objective C and iPhone/iPad/iPod.

#import <UIKit/UIKit.h>

typedef void (^animationCompletionBlock)(void);
#define kAnimationCompletionBlock @"animationCompletionBlock"

@interface ViewController : UIViewController
{
  BOOL animationInFlight;
  IBOutlet UIImageView *imageView;
}
@property (nonatomic) BOOL animationInFlight;

- (IBAction)MaskAnimation:(id)sender;


@end

#import <QuartzCore/QuartzCore.h>
#import "ViewController.h"



@interface ViewController ()

- (void) removePauseForLayer: (CALayer *) theLayer;
@end

@implementation ViewController


@synthesize animationInFlight;

#pragma mark - view lifecycle methods

- (void)viewDidLoad
{
  [super viewDidLoad];
}


//We only support portrait and portrait upside down orientations
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}


- (void)viewDidUnload
{
  imageView = nil;
  [super viewDidUnload];
  // Release any retained subviews of the main view.
}

#pragma mark - Instance methods

- (IBAction)MaskAnimation:(id)sender;
{
    animationCompletionBlock theBlock;
    imageView.hidden = FALSE;//Show the image view
   
    //Create a shape layer that we will use as a mask for the  image view
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
   
   
   
    CGFloat maskHeight = imageView.layer.bounds.size.height;
    CGFloat maskWidth = imageView.layer.bounds.size.width;
   
   
    CGPoint centerPoint;
    centerPoint = CGPointMake( maskWidth/2, maskHeight/2);
   
    //Make the radius of our arc large enough to reach into the corners of the image view.
    CGFloat radius = sqrtf(maskWidth * maskWidth + maskHeight * maskHeight)/2;
    //  CGFloat radius = MIN(maskWidth, maskHeight)/2;
   
    //Don't fill the path, but stroke it in black.
    maskLayer.fillColor = [[UIColor clearColor] CGColor];
    maskLayer.strokeColor = [[UIColor blackColor] CGColor];
   
    maskLayer.lineWidth = radius; //Make the line thick enough to completely fill the circle we're drawing
    //  maskLayer.lineWidth = 10; //Make the line thick enough to completely fill the circle we're drawing
   
    CGMutablePathRef arcPath = CGPathCreateMutable();
   
    //Move to the starting point of the arc so there is no initial line connecting to the arc
    CGPathMoveToPoint(arcPath, nil, centerPoint.x, centerPoint.y-radius/2);
   
    //Create an arc at 1/2 our circle radius, with a line thickess of the full circle radius
    CGPathAddArc(arcPath,
                 nil,
                 centerPoint.x,
                 centerPoint.y,
                 radius/2,
                 3*M_PI/2,
                 -M_PI/2,
                 NO);
   
    maskLayer.path = arcPath;
   
    //Start with an empty mask path (draw 0% of the arc)
    maskLayer.strokeEnd = 0.0;
   
   
    CFRelease(arcPath);
   
    //Install the mask layer into out image view's layer.
    imageView.layer.mask = maskLayer;
   
    //Set our mask layer's frame to the parent layer's bounds.
    imageView.layer.mask.frame = imageView.layer.bounds;
   
    //Create an animation that increases the stroke length to 1, then reverses it back to zero.
    CABasicAnimation *swipe = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    swipe.duration = 2;
    swipe.delegate = self;
    [swipe setValue: theBlock forKey: kAnimationCompletionBlock];
   
    swipe.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    swipe.fillMode = kCAFillModeForwards;
    swipe.removedOnCompletion = NO;
    swipe.autoreverses = YES;
   
    swipe.toValue = [NSNumber numberWithFloat: 1.0];
   
    self.animationInFlight = TRUE;
  
    //Set up a completion block that will be called once the animation is completed.
    theBlock = ^void(void)
    {   
        imageView.layer.mask = nil;
        self.animationInFlight = FALSE;
        imageView.hidden = TRUE;
       
        if (self.view.layer.speed == 0)
            [self removePauseForLayer: self.view.layer];
    };
   
    /*
     Install the completion block in the animation using the key kAnimationCompletionBlock
     The completion block will be run by in the animation's animationDidStop:finished delegate method.
     This approach doesn't work for animations that are part of a group, unfortunately, since an animation's
     delegate methods don't get called when the animation is part of an animation group
     */
   
    [swipe setValue: theBlock forKey: kAnimationCompletionBlock];
   
    [maskLayer addAnimation: swipe forKey: @"strokeEnd"];
   
}


- (void) removePauseForLayer: (CALayer *) theLayer;
{
    theLayer.speed = 1.0;
    theLayer.timeOffset = 0.0;
    theLayer.beginTime = 0.0;
}

#pragma mark - CAAnimation delegate methods

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
  animationCompletionBlock theBlock = [theAnimation valueForKey: kAnimationCompletionBlock];
  if (theBlock)
    theBlock();
}


@end

How to move an object using touch event in iPhone?

Hello friends,
Here is the example regarding moving an object in Objective C or iPhone/iPad/iPod development.


#import <UIKit/UIKit.h>

@interface ImageMoveViewController : UIViewController
{
    IBOutlet UIImageView *photo;
}

@end


#import "ImageMoveViewController.h"

@implementation ImageMoveViewController

/*
 Implement viewDidLoad if you need to do additional setup after loading the view.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // get touch event
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
   
    if ([touch view] == photo) {
        // move the image view
        photo.center = touchLocation;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}
- (void)dealloc {
    [super dealloc];
}

@end


Thanks,
Nilesh M. Prajapati

Thursday, September 27, 2012

UIPanGestureRecognizer scrolling example for iOS

Hi everyone,
Today, I'm giving you the source code of UIPanGestureRecognizer for iPhone.



Follow 2-3 simple steps as given below:

1) Put below code into your .header file of any viewcontroller class.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIGestureRecognizerDelegate>
{
    IBOutlet UIView *viewOrange;
    IBOutlet UIView *viewBrown;
    IBOutlet UIView *viewPurple;
}
@property(nonatomic,retain) IBOutlet UIView *viewOrange;
@property(nonatomic,retain) IBOutlet UIView *viewBrown;
@property(nonatomic,retain) IBOutlet UIView *viewPurple;

@end

2) Put below code into your .m file of same viewcontroller class.

#import "ViewController.h"

@implementation ViewController
@synthesize viewOrange;
@synthesize viewBrown;
@synthesize viewPurple;

CGPoint translatedPoint;
NSInteger _firstX;
NSInteger _firstY;
NSInteger numberofView;
CGSize viewSize;
float currentView;

BOOL isBegan;


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
  
    numberofView = 3;
    viewSize = CGSizeMake(320.0, 480.0);
   
    viewOrange.frame = CGRectMake(0.0, 0.0, 320.0, 480.0);
    viewPurple.frame = CGRectMake(320.0, 0.0, 320.0, 480.0);
    viewBrown.frame = CGRectMake(640.0, 0.0, 320.0, 480.0);
   
    UISwipeGestureRecognizer *swipegestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipe:)];
    [swipegestureRecognizer setDelegate:self];
    [self.view addGestureRecognizer:swipegestureRecognizer];
    [swipegestureRecognizer release];

}

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


-(IBAction)handleSwipe:(UIPanGestureRecognizer *)sender
{
    translatedPoint = [sender translationInView:self.view];

        if([sender state] == UIGestureRecognizerStateBegan)
        {
            if (self.viewOrange.frame.origin.x >= -((numberofView-1)*viewSize.width) && self.viewOrange.frame.origin.x <= 0.0)
            {
                _firstX = self.viewOrange.frame.origin.x;
                _firstY = self.viewOrange.frame.origin.y;
               
                if (viewOrange.frame.origin.x==0) {
                    currentView=0;
                }else if (viewPurple.frame.origin.x==0) {
                    currentView=1;
                }else if (viewBrown.frame.origin.x==0) {
                    currentView=2;
                }

            }
        }
        else if([sender state] == UIGestureRecognizerStateChanged)
        {
            if ([sender velocityInView:self.view].x >= 600.0)
            {
                if (!isBegan)
                {
                    if (self.viewOrange.frame.origin.x < 0.0)
                    {
                        isBegan = YES;
                        NSLog(@"Velocity Changed.");
                        [UIView beginAnimations:nil context:NULL];
                        [UIView setAnimationDuration:0.2];
                        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                        [viewOrange setFrame:CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                        viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                        viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                        [UIView commitAnimations];
                    }
                }
            }
            else if ([sender velocityInView:self.view].x <= -600.0)
            {
                if (!isBegan)
                {
                    if (self.viewOrange.frame.origin.x > -((numberofView-1)*viewSize.width))
                    {
                        isBegan = YES;
                        NSLog(@"Velocity Changed.");
                        [UIView beginAnimations:nil context:NULL];
                        [UIView setAnimationDuration:0.2];
                        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                        [viewOrange setFrame:CGRectMake(viewOrange.frame.origin.x - viewOrange.frame.size.width, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                        viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                        viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                        [UIView commitAnimations];
                    }
                }
            }
            else
            {
                if (self.viewOrange.frame.origin.x >= -((numberofView-1)*viewSize.width) && self.viewOrange.frame.origin.x <= 0.0)
                {
                    NSLog(@"State Changed.");
                    [UIView beginAnimations:nil context:NULL];
                    [UIView setAnimationDuration:0.2];
                    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                    translatedPoint = CGPointMake(_firstX + translatedPoint.x, 0.0);
                    [viewOrange setFrame:CGRectMake(translatedPoint.x, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                    viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                    viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                    [UIView commitAnimations];
                }
            }
        }
        else if([sender state] == UIGestureRecognizerStateEnded)
        {
            NSLog(@"State Ended On That ");
            if (self.viewOrange.frame.origin.x >= -((numberofView-1)*viewSize.width) && self.viewOrange.frame.origin.x <= 0.0)
            {
                NSLog(@"%f",viewOrange.frame.origin.x);
                NSLog(@"%f",viewPurple.frame.origin.x);
                NSLog(@"%f",viewBrown.frame.origin.x);
                if (currentView==0) {
                    if (viewOrange.frame.origin.x<0 ){
                        if (viewOrange.frame.origin.x<-160) {
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-320, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(viewOrange.frame.size.width+viewOrange.frame.origin.x , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            [UIView commitAnimations];
                        }else{
                           
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(0.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(320, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            [UIView commitAnimations];
                        }
                    }
                }else if(currentView==1){
                    if (viewPurple.frame.origin.x<0){
                        if (viewPurple.frame.origin.x<-160) {
                           
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-640, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(-320 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(0.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                           
                          

                        }else {
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-320.0, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(0.0 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(320.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                        }
                    }else{
                         if (viewPurple.frame.origin.x>160) {
                             [UIView beginAnimations:nil context:NULL];
                             [UIView setAnimationDuration:0.2];
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                             [viewOrange setFrame:CGRectMake(0.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                             viewPurple.frame = CGRectMake(320 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                             viewBrown.frame = CGRectMake(640.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                             [UIView commitAnimations];

                         }else{
                            
                             [UIView beginAnimations:nil context:NULL];
                             [UIView setAnimationDuration:0.2];
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                             [viewOrange setFrame:CGRectMake(-320.0, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                             viewPurple.frame = CGRectMake(0.0 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                             viewBrown.frame = CGRectMake(320.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                             [UIView commitAnimations];
                            
                        }
                    }
                }else if(currentView==2){
                    if (viewBrown.frame.origin.x>0){
                       
                        if (viewBrown.frame.origin.x>160) {
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-320.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(0.0 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(320.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                        }else{
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-640, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(-320 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(0.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                           
                        }
                      
                    }
                }
            }
            isBegan = NO;
            if (self.viewOrange.frame.origin.x <-((numberofView-1)*viewSize.width))
            {
                NSLog(@"State Changed.");
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:0.2];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                [viewOrange setFrame:CGRectMake(-640.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                [UIView commitAnimations];
            }
            else if (self.viewOrange.frame.origin.x > 0)
            {
                NSLog(@"State Changed.");
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:0.2];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                [viewOrange setFrame:CGRectMake(0.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                [UIView commitAnimations];
            }
        }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


@end

 Thanks,
Nilesh Prajapati

Saturday, September 22, 2012

how to detect link in UIWebview?

Hi friends,
Again I'm here to share something new with you.. If you want to do some operations on URL click in UIWebview of iPhone/iPod/iPad then you need to use the below delegate method of UIWebview. You have to set WebViewDelegate in header file of your class.


#pragma mark-------------------------
#pragma mark WebView Delegate Method


- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = request.URL;
    NSString *urlString = url.relativeString;
    NSLog(@"%@",urlString);
    NSLog(@"%@",[request.URL lastPathComponent]);
    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        if([[urlString substringToIndex:5] isEqualToString:@"https"] || [[urlString substringToIndex:5] isEqualToString:@"http:"])
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString: urlString]];
        }
        else
        {
               // do your operation within Application
        }
        return NO;
    }
    return YES;
}

Hope you like this..

Thanks ,
Nilesh Prajapati

Tuesday, August 28, 2012

In-App Purchase Tutorial in iPhone

Hi,
Everyone, 
Here, I'm going to start the explanation for In-App Purchase for non-consumable product in iPhone/iPad. 

 You have to follow the below steps before you implement the code given below:


 After Creating new APP Id and making In-App Purchase Enabled , You have to create product identifier for non-consumable purchase and need to fill all required information .

After completion all process to itunesconnect.apple.com, you can implement the below code into you project file.

#import <StoreKit/StoreKit.h>
#define kMyFeatureIdentifier @"" //Product Identifier in In-App Purchase

@interface AppDelegate : UIResponder <UIApplicationDelegate,SKPaymentTransactionObserver ,SKRequestDelegate, SKProductsRequestDelegate>
{
    NSArray *arrPurchaseProducts;
    SKProduct *product;
}



#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if([SKPaymentQueue canMakePayments])
    {
        if (![[NSUserDefaults standardUserDefaults] valueForKey:@"isPurchased"])
        {
            // restarts any purchases if they were interrupted last time the app was open
            [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
            [self requestProductData];
        }
        NSLog(@"IN-APP:can make payments");
    }
    else {
        NSLog(@"IN-APP:can't make payments");
    }
}
   

#pragma mark -
#pragma User-Defined Method for Restore product functionality

-(void)checkPurchasedItems
{
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

#pragma mark -
#pragma mark In-App Purchase Delegate Methods

- (void)requestProductData
{

    NSLog(@"IN-APP:requestProductData");
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kMyFeatureIdentifier]];
    request.delegate = self;
    [request start];
    NSLog(@"IN-APP:requestProductData END"); 
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSLog(@"IN-APP:productsRequest");
    NSArray *myProduct = [[NSArray alloc]initWithArray:response.products];
    if ([myProduct count]>0)
    {
        SKProduct *product = [myProduct objectAtIndex:0];
        NSLog(@"Price: %.2f",product.price.floatValue);
        NSLog(@"Price Locale: %@",product.priceLocale.localeIdentifier);
        NSLog(@"Product Identifier: %@",product.productIdentifier);
        NSLog(@"IN-APP:array count: %i", [myProduct count]);
        [request autorelease];
        NSLog(@"IN-APP:productsRequest END");
    }
    [myProduct release];
    myProduct = nil;
}

-(void)buyProduct
{
    SKPayment *payment = [SKPayment paymentWithProductIdentifier:kMyFeatureIdentifier];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
    payment = nil;
//    if (arrPurchaseProducts.count>0)
//    {
//        SKProduct *selectedProduct = [arrPurchaseProducts objectAtIndex:0];
//        SKPayment *payment = [SKPayment paymentWithProduct:selectedProduct];
//        [[SKPaymentQueue defaultQueue] addPayment:payment];
//        selectedProduct = nil;
//        payment = nil;
//    }
}

#pragma mark -
#pragma mark SKPaymentTransactionObserver methods

// called when the transaction status is updated
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"Purchasing...");
                break;
            default:
                break;
        }
    }
}


#pragma -
#pragma Purchase helpers

// saves a record of the transaction by storing the receipt to disk
- (void)recordTransaction:(SKPaymentTransaction *)transaction
{
    if ([transaction.payment.productIdentifier isEqualToString:kMyFeatureIdentifier])
    {
        // save the transaction receipt to disk
        [[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@"proUpgradeTransactionReceipt"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

// enable pro features
- (void)provideContent:(NSString *)productId
{
    if ([productId isEqualToString:kMyFeatureIdentifier])
    {
        // enable the pro features
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPurchased"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}


// removes the transaction from the queue and posts a notification with the transaction result
- (void)finishTransaction:(SKPaymentTransaction *)transaction wasSuccessful:(BOOL)wasSuccessful
{
    // remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:transaction, @"transaction" , nil];
    if (wasSuccessful)
    {
        // send out a notification that we’ve finished the transaction
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PurchaseSuccess" object:self userInfo:userInfo];
    }
    else
    {
        // send out a notification for the failed transaction
       // [[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerTransactionFailedNotification object:self userInfo:userInfo];
    }
}

// called when the transaction was successful
- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
    [self recordTransaction:transaction];
    [self provideContent:transaction.payment.productIdentifier];
    [self finishTransaction:transaction wasSuccessful:YES];
}

// called when a transaction has been restored and and successfully completed
- (void)restoreTransaction:(SKPaymentTransaction *)transaction
{
    [self recordTransaction:transaction.originalTransaction];
    [self provideContent:transaction.originalTransaction.payment.productIdentifier];
    [self finishTransaction:transaction wasSuccessful:YES];
}

// called when a transaction has failed
- (void)failedTransaction:(SKPaymentTransaction *)transaction
{
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        // error!
        [self finishTransaction:transaction wasSuccessful:NO];
        if (transaction.error.code == SKErrorClientInvalid) {
            [self showAlert:@"In-App Purchase" withMessage:INVALID_CLIENT];
        }
        else if (transaction.error.code == SKErrorPaymentInvalid) {
            [self showAlert:@"In-App Purchase" withMessage:PAYMENT_INVALID];
        }
        else if (transaction.error.code == SKErrorPaymentNotAllowed) {
            [self showAlert:@"In-App Purchase" withMessage:PAYMENT_NOT_ALLOWED];
        }
        else if (transaction.error.code == SKErrorPaymentCancelled) {
           // [self showAlert:@"In-App Purchase" withMessage:@"This device is not allowed to make the payment."];
            NSLog(@"User Cancellation.");
        }
        else {
           // SKErrorUnknown
            NSLog(@"Unknown Reason.");
        }
    }
    else  {
        // this is fine, the user just cancelled, so don’t notify
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }
}

//Then this delegate Funtion Will be fired
- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
    NSLog(@"received restored transactions: %i", queue.transactions.count);
    for (SKPaymentTransaction *transaction in queue.transactions)
    {
        NSString *productID = transaction.payment.productIdentifier;
    }
   
}