Powered By Blogger

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;
    }
   
}

Wednesday, August 8, 2012

NSDateFormatter Example in iPhone SDK

Hi,
Every one,
I'm going to share NSDateFormatter examples for iPhone/iPad Applications. Please check below code reference :

+(NSString *)returnDateString:(NSDate *)date
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    NSLocale *usLocale = [NSLocale systemLocale];
    [formatter setLocale:usLocale];
    usLocale = nil;
    return [formatter stringFromDate:date];
}

+(NSString *)returnDateStringWithTime:(NSDate *)date
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLocale *usLocale = [NSLocale systemLocale];
    [formatter setLocale:usLocale];
    usLocale = nil;
    return [formatter stringFromDate:date];
}

+(NSDate *)returnFormattedStringWithDate:(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
       NSLocale *usLocale = [NSLocale systemLocale];
    [dateFormatter setLocale:usLocale];
    usLocale = nil;
    return [dateFormatter dateFromString:dateString];
}

Here is the list of the string formats that can be used with NSDateFormatter in iPhone/iPad Applications.

a: AM/PM
A: 0~86399999 (Millisecond of Day)

c/cc: 1~7 (Day of Week)
ccc: Sun/Mon/Tue/Wed/Thu/Fri/Sat
cccc: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

d: 1~31 (0 padded Day of Month)
D: 1~366 (0 padded Day of Year)

e: 1~7 (0 padded Day of Week)
E~EEE: Sun/Mon/Tue/Wed/Thu/Fri/Sat
EEEE: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

F: 1~5 (0 padded Week of Month, first day of week = Monday)

g: Julian Day Number (number of days since 4713 BC January 1)
G~GGG: BC/AD (Era Designator Abbreviated)
GGGG: Before Christ/Anno Domini

h: 1~12 (0 padded Hour (12hr))
H: 0~23 (0 padded Hour (24hr))

k: 1~24 (0 padded Hour (24hr)
K: 0~11 (0 padded Hour (12hr))

L/LL: 1~12 (0 padded Month)
LLL: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
LLLL: January/February/March/April/May/June/July/August/September/October/November/December

m: 0~59 (0 padded Minute)
M/MM: 1~12 (0 padded Month)
MMM: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
MMMM: January/February/March/April/May/June/July/August/September/October/November/December

q/qq: 1~4 (0 padded Quarter)
qqq: Q1/Q2/Q3/Q4
qqqq: 1st quarter/2nd quarter/3rd quarter/4th quarter
Q/QQ: 1~4 (0 padded Quarter)
QQQ: Q1/Q2/Q3/Q4
QQQQ: 1st quarter/2nd quarter/3rd quarter/4th quarter

s: 0~59 (0 padded Second)
S: (rounded Sub-Second)

u: (0 padded Year)

v~vvv: (General GMT Timezone Abbreviation)
vvvv: (General GMT Timezone Name)

w: 1~53 (0 padded Week of Year, 1st day of week = Sunday, NB: 1st week of year starts from the last Sunday of last year)
W: 1~5 (0 padded Week of Month, 1st day of week = Sunday)

y/yyyy: (Full Year)
yy/yyy: (2 Digits Year)
Y/YYYY: (Full Year, starting from the Sunday of the 1st week of year)
YY/YYY: (2 Digits Year, starting from the Sunday of the 1st week of year)

z~zzz: (Specific GMT Timezone Abbreviation)
zzzz: (Specific GMT Timezone Name)
Z: +0000 (RFC 822 Timezone)



Thanks & Regards,
Nilesh Prajapati

Wednesday, August 1, 2012

how to make custom tabbar in iphone?

Hello,
Just like as every time, I'm here to share code regarding "Custom Tabbar" in iPhone/iPad Application.

Please take a look..

Step 1:  Place these two files in to your project... "CustomTabBar.h" and "CustomTabBar.m"

#import <UIKit/UIKit.h>

@interface CustomTabBar : UITabBarController {
    UIButton *btn1;
    UIButton *btn2;
    UIButton *btn3;
    UIButton *btn4;
    UIButton *btn5;
}

@property (nonatomic, retain) UIButton *btn1;
@property (nonatomic, retain) UIButton *btn2;
@property (nonatomic, retain) UIButton *btn3;
@property (nonatomic, retain) UIButton *btn4;
@property (nonatomic, retain) UIButton *btn5;

-(void) hideTabBar;
-(void) addCustomElements;
-(void) selectTab:(int)tabID;

@end


#import "CustomTabBar.h"

@implementation CustomTabBar

@synthesize btn1, btn2, btn3, btn4, btn5;

- (void)viewDidAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self hideTabBar];
    [self addCustomElements];
}

-(void)hideTabBar
{
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            view.hidden = YES;
            break;
        }
    }
}

-(void)hideNewTabBar
{
    self.btn1.hidden = 1;
    self.btn2.hidden = 1;
    self.btn3.hidden = 1;
    self.btn4.hidden = 1;
    self.btn5.hidden = 1;
}

- (void)showNewTabBar
{
    self.btn1.hidden = 0;
    self.btn2.hidden = 0;
    self.btn3.hidden = 0;
    self.btn4.hidden = 0;
    self.btn5.hidden = 0;
}

-(void)addCustomElements
{
    // Initialise our two images
    UIImage *btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    UIImage *btnImageSelected = [UIImage imageNamed:@"NavBar_01_s.png"];
   
    self.btn1 = [UIButton buttonWithType:UIButtonTypeCustom]; //Setup the button
    btn1.frame = CGRectMake(0, 430, 80, 50); // Set the frame (size and position) of the button)
    [btn1 setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button
    [btn1 setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button
    [btn1 setTag:0]; // Assign the button a "tag" so when our "click" event is called we know which button was pressed.
    [btn1 setSelected:true]; // Set this button as selected (we will select the others to false as we only want Tab 1 to be selected initially
   
    // Now we repeat the process for the other buttons
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_02_s.png"];
    self.btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(80, 430, 80, 50);
    [btn2 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn2 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn2 setTag:1];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_03_s.png"];
    self.btn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn3.frame = CGRectMake(160, 430, 80, 50);
    [btn3 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn3 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn3 setTag:2];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_04_s.png"];
    self.btn4 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn4.frame = CGRectMake(240, 430, 80, 50);
    [btn4 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn4 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn4 setTag:3];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_04_s.png"];
    self.btn5 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn5.frame = CGRectMake(320, 430, 80, 50);
    [btn5 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn5 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn5 setTag:4];
   
   
    // Add my new buttons to the view
    [self.view addSubview:btn1];
    [self.view addSubview:btn2];
    [self.view addSubview:btn3];
    [self.view addSubview:btn4];
    [self.view addSubview:btn5];

   
    // Setup event handlers so that the buttonClicked method will respond to the touch up inside event.
    [btn1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn2 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn3 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn4 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn5 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonClicked:(id)sender
{
    int tagNum = [sender tag];
    [self selectTab:tagNum];
}

- (void)selectTab:(int)tabID
{
    switch(tabID)
    {
        case 0:
            [btn1 setSelected:true];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 1:
            [btn1 setSelected:false];
            [btn2 setSelected:true];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 2:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:true];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 3:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:true];
            [btn5 setSelected:false];
            break;
        case 4:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:true];
            break;
    }   
    self.selectedIndex = tabID;
}

- (void)dealloc {
    [btn1 release];
    [btn2 release];
    [btn3 release];
    [btn4 release];
    [btn5 release];
    [super dealloc];
}

Step 2 :  If you user XIB base TabBarController then you need to set "CustomTabBar" as its class or otherwise you have to create TabBarController object of "CustomTabBar" class .

Now , you are able to use custom tabbar into user application. one more thing, You have to add the images which you want to assign at your tabbar controller items.

Thanks & Regards,
Nilesh Prajapati