Friday, 18 April 2014

Store a Bool Value or String Value in Your App

Storing Process :
You can Store values are these methods :
setValue, setURL, setInteger, setDouble, setFloat, setBool, setObject and more........

Example :
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"BoolValue"];
[[NSUserDefaults standardUserDefaults] synchronize];

[[NSUserDefaults standardUserDefaults] setObject:@"str" forKey:@"key"];
[[NSUserDefaults standardUserDefaults] synchronize];

[[NSUserDefaults standardUserDefaults] setInteger:12 forKey:@"Int"];
[[NSUserDefaults standardUserDefaults] synchronize];

Retrive Process :
Example 1:
NSString *String_Str = [[NSUserDefaults standardUserDefaults]boolForKey:@"BoolValue"];
if (!String_Str)
{
        //Code
}
else
{
       //Code
}

Example 2:
NSString *String_Str1 = [[NSUserDefaults standardUserDefaults]boolForKey:@"key"];
NSLog(String_Str1);

Example Program - In App Purchase

.h File
#import <UIKit/UIKit.h>
#import <StoreKit/StoreKit.h>

@interface inapp_purchase : UIViewController<SKPaymentTransactionObserver,SKProductsRequestDelegate>
{
    IBOutlet UILabel *iTitle;
    IBOutlet UILabel *idescription;
    IBOutlet UILabel *iPrice;
    IBOutlet UILabel *ipricelabel;
    
    IBOutlet UIButton *ibuy;
    IBOutlet UIButton *irestore;
    
    IBOutlet UIActivityIndicatorView *loader;
}
@end

.m File
#import "inapp_purchase.h"
@interface inapp_purchase ()
{
    SKProductsRequest *_productsRequest;
    NSArray *_products;
    NSNumberFormatter *_priceFormatter;
    SKProduct *proUpgradeProduct;
}
@end

@implementation inapp_purchase

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    _priceFormatter = [[NSNumberFormatter alloc] init];
    [_priceFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [_priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    
    _products = nil;
    
    [loader startAnimating];
    
    [self requestProUpgradeProductData];
}

- (void)requestProUpgradeProductData
{
    NSSet *productIdentifiers = [NSSet setWithObject:@"com.ashuss.WedPlanPremium" ];
    _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    _productsRequest.delegate = self;
    [_productsRequest start];
    
    // we will release the request object in the delegate callback
}

#pragma mark -
#pragma mark SKProductsRequestDelegate methods
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSArray *products = response.products;
    proUpgradeProduct = [products count] == 1 ? [[products firstObject] retain] : nil;
    _products = products;
    if (proUpgradeProduct)
    {
        iTitle.text = proUpgradeProduct.localizedTitle;
        [_priceFormatter setLocale:proUpgradeProduct.priceLocale];
        iPrice.text = [_priceFormatter stringFromNumber:proUpgradeProduct.price];
        idescription.text = proUpgradeProduct.localizedDescription;
        
        ipricelabel.hidden = NO;
        ibuy.hidden = NO;
        irestore.hidden = NO;
        
        [loader stopAnimating];
        
        NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
        NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
        NSLog(@"Product price: %@" , proUpgradeProduct.price);
        NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
    }
    
    for (NSString *invalidProductId in response.invalidProductIdentifiers)
    {
        NSLog(@"Invalid product id: %@" , invalidProductId);
    }
    
    // finally release the reqest we alloc/init’ed in requestProUpgradeProductData
    [_productsRequest release];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kInAppPurchaseManagerProductsFetchedNotification" object:self userInfo:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    SKProduct * product = (SKProduct *) _products[0];
    iTitle.text = product.localizedTitle;
    [_priceFormatter setLocale:product.priceLocale];
    iPrice.text = [_priceFormatter stringFromNumber:product.price];
    idescription.text = product.description;
}

- (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];
            default:
                break;
        }
    }
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction{
    NSLog(@"Transaction Completed");
    // You can create a method to record the transaction.
    //[self recordTransaction: transaction];
    
    // You should make the update to your app based on what was purchased and inform user.
    [self provideContent: transaction.payment.productIdentifier];
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

-(void)provideContent: (NSString *)productIdentifier
{
    if ([productIdentifier isEqualToString:@"com.ashuss.WedPlanPremium"])
    {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"InAppPurchase" object:productIdentifier userInfo:nil];
        //do your stup because purchase completeded
        single.ads_removed = YES;
        [self dismissModalViewControllerAnimated:YES];
    }
    else
    {
        NSLog(@"Failed");
    }
}

- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@"Transaction Restored");
    // You can create a method to record the transaction.
    // [self recordTransaction: transaction];
    
    // You should make the update to your app based on what was purchased and inform user.
    [self provideContent: transaction.payment.productIdentifier];
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
    //[activityIndicator stopAnimating];
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        // Display an error here.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Purchase Unsuccessful"
                                                        message:@"Your purchase failed. Please try again."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

-(IBAction)done:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

-(IBAction)Buy:(id)sender
{
    SKPayment *newPayment = [SKPayment paymentWithProduct:proUpgradeProduct];
    [[SKPaymentQueue defaultQueue] addPayment:newPayment];
}

-(IBAction)Restore:(id)sender
{
    [[SKPaymentQueue defaultQueue]restoreCompletedTransactions];
}

Tuesday, 15 April 2014

In-App-Purchase in iOS

Step 1 :iTunes Connect (Login Ur Account) -> Manage Subscriptions -> App(Which One) -> Manage the InAppPurchase -> Select Type -> Create a Product id (ex:com.ashuss.AppPremium) -> Approve.

Step 2 : In Project Header --> Tab the Capabilities --> InApp Purchase to Enable it.



Step 3: Add a StoreKit.framwork into Your Project

Step 4: Add the In-App-Purchase Code into Your Project

-(void)viewWillAppear:(BOOL)animated 
           (or)
-(void)viewDidLoad
{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

-(IBAction)Btn_Click:(id)sender
{
    BOOL productpurchased = [[NSUserDefaults standardUserDefaults] boolForKey:@"com.ashuss.AppPremium"];
    if (productpurchased)
    {
        //iPhone_HSMO *vmo = [[iPhone_HSMO alloc]init];
        //[self.navigationController pushViewController:vmo animated:YES];
    }
    else
    {
        objAlert = [[UIAlertView alloc]initWithTitle:@"App Premium" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Restore",@"Buy", nil];
        [objAlert show];
        [objAlert setTag:1];
    }
}

-(void)alertView:(UIAlertView *)objAlert didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ([objAlert tag]==1)
{
if (buttonIndex==0)
{
[[SKPaymentQueue defaultQueue]restoreCompletedTransactions];
}
else if (buttonIndex==1)
{
SKProductsRequest *request= [[SKProductsRequest alloc]initWithProductIdentifiers: [NSSet setWithObject: @"com.ashuss.AppPremium"]];
            request.delegate = self;
            [request start];
}
}
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    NSArray *myProduct = response.products;
    NSLog(@"%@",[[myProduct objectAtIndex:0] productIdentifier]);
    
    //Since only one product, we do not need to choose from the array. Proceed directly to payment.
    
    SKPayment *newPayment = [SKPayment paymentWithProduct:[myProduct objectAtIndex:0]];
    [[SKPaymentQueue defaultQueue] addPayment:newPayment];
    
    [request autorelease];
}

- (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];
            default:
                break;
        }
    }
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@"Transaction Completed");
    // You can create a method to record the transaction.
    //[self recordTransaction: transaction];
    
    // You should make the update to your app based on what was purchased and inform user.
    [self provideContent: transaction.payment.productIdentifier];
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@"Transaction Restored");
    // You can create a method to record the transaction.
    // [self recordTransaction: transaction];
    
    // You should make the update to your app based on what was purchased and inform user.
    [self provideContent: transaction.payment.productIdentifier];
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

-(void)provideContent: (NSString *)productIdentifier
{
    if ([productIdentifier isEqualToString:@"com.ashuss.AppPremium"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
        //[[NSUserDefaults standardUserDefaults] setDouble:1.11 forKey:aa];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"InAppPurchase" object:productIdentifier userInfo:nil];
        
        iPhone_HSMO *vmo = [[iPhone_HSMO alloc]init];
        [self.navigationController pushViewController:vmo animated:YES];
    }
    else
    {
        NSLog(@"Failed");
    }
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
    //[activityIndicator stopAnimating];
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        // Display an error here.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Purchase Unsuccessful"
                                                        message:@"Your purchase failed. Please try again."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


Wednesday, 2 April 2014

iPhone/iOS/iPad/Apple Sample Code

Sample code is one of the most useful tools for learning about programming. Here's a collection of links I've found so far. Does anyone know of some other sources for iPhone sample code?

Just sample code:
    •    Google Code: http://code.google.com/hosting/search?q=label%3Aiphone
    •    iPhone Cool Projects: http://www.apress.com/book/view/143022357x
    •    iPhone Game Projects: http://www.apress.com/book/downloadfile/4419
    •    Learn Objective-C on the Mac: http://www.apress.com/book/downloadfile/4175
    •    Code4App: http://code4app.net/
    •    iCode Blog: http://icodeblog.com/
    •    Raywenderlich Tutorials: http://www.raywenderlich.com/
    •    OpenGLS: http://iphonedevelopment.blogspot.com/2009/05/opengl-es-from-ground-up-table-of.html


Apple Sample Code:

Apps Amuck 31 days:

Beginning iPhone Development:

Chris Software:

Dave DeLong's downloads:
     
Delicious.com: 

iPhone Developer's Cookbook: 

iPhone SDK source code:

Joe Hewitt three20:

Stanford iPhone code:

WiredBob (TabBar in Detail view):

BYU Cocoaheads :

Big Nerd Ranch:

Cocoa with love:

Will Shipley:

mobile.tuts:

Wednesday, 19 March 2014

Image Processing : Image Colour Changed

Image Processing : Image Colour Changed when Slider Value is Changed 

Framework :
  Core Image Framework added into Your project

New.h :
#import <UIKit/UIKit.h>
#import <CoreImage/CoreImage.h> 
@interface New : UIViewController
{
    UIImage *Imagesss;
    IBOutlet UIImageView *theImageView;
    IBOutlet UISlider *slider_hue;
}
@property (nonatomic, retain) IBOutlet UISlider *slider_hue;
@property (nonatomic, retain) IBOutlet UIImageView *theImageView;

-(IBAction)huechange:(id)sender;
-(IBAction)huevaluechange:(id)sender;
- (IBAction)original:(id)sender;

@end

New.m :
@synthesize theImageView, slider_hue;

- (void)viewDidLoad
{
    [super viewDidLoad];
    Imagesss = [UIImage imageNamed:@"hair.png"];
}

- (IBAction)original:(id)sender
{
    theImageView.image = [UIImage imageNamed:@"hair.png"];
}

//Method 1
-(IBAction)huevaluechange:(id)sender
{
    float f= slider_hue.value;
    
    UIImage *image = [self imageWithImage:Imagesss rotatedByHue:f];
    
    [theImageView setImage:image];
}

//Method 2
-(IBAction)huechange:(id)sender
{
    float f= slider_hue.value;
   
    UIImage *image = [self imageWithImage:[UIImage imageNamed:@"hair.png"] fixedHue:f alpha:1.0];

    [theImageView setImage:image];
}

//Method 1 - Function
- (UIImage*) imageWithImage:(UIImage*) source rotatedByHue:(CGFloat) deltaHueRadians;
{
    // Create a Core Image version of the image.
    CIImage *sourceCore = [CIImage imageWithCGImage:[source CGImage]];

    // Apply a CIHueAdjust filter
    CIFilter *hueAdjust = [CIFilter filterWithName:@"CIHueAdjust"];
    [hueAdjust setDefaults];
    [hueAdjust setValue: sourceCore forKey: @"inputImage"];
    [hueAdjust setValue: [NSNumber numberWithFloat: deltaHueRadians] forKey: @"inputAngle"];
    CIImage *resultCore = [hueAdjust valueForKey: @"outputImage"];
    
    // Convert the filter output back into a UIImage.
    // This section from http://stackoverflow.com/a/7797578/1318452
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef resultRef = [context createCGImage:resultCore fromRect:[resultCore extent]];
    UIImage *result = [UIImage imageWithCGImage:resultRef];
    CGImageRelease(resultRef);
    return result;
}

//Method 2 - Function
- (UIImage*) imageWithImage:(UIImage*) source fixedHue:(CGFloat) hue alpha:(CGFloat) alpha;
{
     // Note: the hue input ranges from 0.0 to 1.0, both red.  Values outside this range will be clamped to 0.0 or 1.0.

    // Find the image dimensions.
    CGSize imageSize = [source size];
    CGRect imageExtent = CGRectMake(0,0,imageSize.width,imageSize.height);
    
    // Create a context containing the image.
    UIGraphicsBeginImageContext(imageSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [source drawAtPoint:CGPointMake(0,0)];
    
    // Draw the hue on top of the image.
    CGContextSetBlendMode(context, kCGBlendModeHue);
    [[UIColor colorWithHue:hue saturation:1.0 brightness:1.0 alpha:alpha] set];
    UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:imageExtent];
    [imagePath fill];
    
    // Retrieve the new image.
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}


New.xib :
//Method 1 - Slider Value
slider value is range from 0 to 6

//Method 2 - Slider Value
slider value is range from 0 to 1

Output :
App Start Page
Change the Slider Value


AppDelegate Method - Store a Variable (Singleton)

AppDelegate.h :
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
 NSString *name;
}
@property(strong,nonatomic)NSString *name;

@end

AppDelegate.m :
 //Nothing Do

SomeFile.h :
#import "AppDelegate.h"
@interface SomeFile : UIViewController
{
    
}
-(IBAction)save:(id)sender;
-(IBAction)retrive:(id)sender;
@end

SomeFile.m :
-(IBAction)save:(id)sender
{
      AppDelegate *del=(AppDelegate *)[[UIApplication sharedApplication]delegate];
      [del setName:txt_name.text];
}

-(IBAction)retrive:(id)sender
{
      AppDelegate *del=(AppDelegate *)[[UIApplication sharedApplication]delegate];
     if (del.name==nil)
     {
           // Login page is showed
     }
     else
     {
           NSString *name = del.name; 
     }
}

Singleton Object Creation

Singleton Object Creation


Defn:


In computer programming a singleton variable is a variable that is referred to only once.
Examples of where a variable might only be referenced once is as a dummy argument in a function call, or when its address is assigned to another variable which subsequently accesses its allocated storage.
Singleton variables sometimes occur because a mistake has been made – such as assigning a value to a variable and forgetting to use it later, or mistyping one instance of the variable name. Some compilers and lint-like tools flag occurrences of singleton variables.

Creating Singleton Object File:

In Sample Project we can add the file in Xcode tool.

File --> New --> File --> Choose Objective-C class --> Next --> 

class Name is "singleton" 
subclass is NSObject is Selected.

Next --> Finish.


singleton.h :

 #import <Foundation/Foundation.h>

@interface Singleton : NSObject

//Create the variables or objects.
@property(nonatomic,assign) float ad_height;
@property(nonatomic,assign) BOOL ads_removed,is_ipad;
@property(nonatomic, assign) CGRect banner_land;
@property(nonatomic, assign) CGRect banner_port;
@property(nonatomic,assign) UIInterfaceOrientation last_orient;


@property(nonatomic,assign) NSString *lastsss;

+(Singleton *)singleObj;  //class method


//-(void)Objsin;   //instance method

@end

singleton.m :

 #import "Singleton.h"

@implementation Singleton

@synthesize lastsss;

+(Singleton *)singleObj     //class Method
{
    
    static Singleton * single=nil;
    
    @synchronized(self)
    {
        if(!single)
        {
            single = [[Singleton alloc] init];
        }
    }
    return single;
}


-(void)Objsin      //instance method
{
    lastsss = @"aaa";

}


@end


SomeFile.h :


#import "Singleton.h"

@interface SomeFile : UIViewController
{
    Singleton *sobj;
}


SomeFile.m :

  //public method. Access from any page. Deallocate when app is closed.
-(void) viewwillappear method
{
   //reference to allocate
   sobj = [Singleton singleObj];    

   //Method calling
   [sobj Objsin];

    //Assign the values
    NSString *str= @"bb";
    sobj.lastsss = str;

    sobj.last_orient = [UIApplication sharedApplication].statusBarOrientation;

    sobj.banner_land = _bannerView.frame;   //CGRect(0, 0, 0, 0)
    sobj.banner_port = _bannerView.frame;   //CGRect(0, 0, 0, 0)

    sobj.ad_height = 40.0;

    sobj.is_ipad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);    //YES or NO

    sobj.ads_removed = NO;
}

               (or)

 //private method. Access only this page. Deallocate when page is moved.
-(void) viewwillappear method
{
    //initiate memory allocation
    sobj = [[Singleton alloc]init];

    //Method calling
    [sobj Objsin]; 


    //Assign the values
    NSString *str= @"bb";
    sobj.lastsss = str;

    sobj.last_orient = [UIApplication sharedApplication].statusBarOrientation;

    sobj.banner_land = _bannerView.frame;   //CGRect(0, 0, 0, 0)
    sobj.banner_port = _bannerView.frame;   //CGRect(0, 0, 0, 0)

    sobj.ad_height = 40.0;

    sobj.is_ipad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);    //YES or NO

    sobj.ads_removed = NO;
}