Search code examples
iosxcodein-app-purchaseskproduct

in app purchase - present price to User


I have two View Controllers. One of them shows the available In App Purchases. When an user selects one of them it presents a new View Controllers containing the details of the Purchase and the "Buy" button.

The way I pass my code from the first view to the second is the following:

-(IBAction)purchase1:(id)sender{
_purchasedController = [[iPadPurchasedViewController alloc] initWithNibName:nil bundle:nil];
_purchasedController.productID = @"xxxxx.xxxxx.xxxxx";
[self presentViewController:_purchasedController animated:YES completion:NULL];
[self.purchasedController getProductID:self];
}

So when a user selects one button I pass the productID string to the second ViewController. However, I wanted to present the price to the user on the first View Controller. Can somebody help me with that? Thank you.


Solution

  • Edited answer to be more complete:

    In your ViewController.h file there should be

    @interface ViewController : UIViewController <SKProductsRequestDelegate> {
        NSArray *allProducts; 
    }
    

    Then in ViewController.m eg. in viewDidload:

    -(void) viewDidload {
        [super viewDidLoad];
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:@"xxxx1",@"xxxx2",nil]];
        request.delegate=self; 
        [request start]; 
    }
    
    -(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
        allProducts = response.products;
        NSLog(@"Fetched %d products", allProducts.count);
     }
    

    And then it can be used as such:

    -(NSString*) getPriceForProductWithID:(NSString*)productID{
    
       if(allProducts.count < 1) {
            NSLog(@"Did not fetch products yet");
       }
       else {
    
           NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
           numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
           [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    
           for(SKProduct * product in allProducts) {
    
               if([product.productIdentifier isEqualToString:productID])
               {
                   [numberFormatter setLocale:product.priceLocale];
    
                   NSString *priceString= [numberFormatter stringFromNumber:product.price];
    
            NSLog(@"Product with ID: %@ has price: %@",product.productIdentifier, priceString);
                  return priceString;
               } 
           }
        }
        return nil;
    }