Genadinik
Genadinik

Reputation: 18629

Not sure how to invoke the buying process for in-app purchases in iOS with Objective-C

I have a method like this

- (IBAction)makePurchase:(id)sender
{
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Starting the purchase"

    message:@"Just press OK." delegate:nil
    cancelButtonTitle:@"OK" otherButtonTitles:nil];

    [message show];

    // Put your product identifiers in an NSSet and perform the appropriate product request (i.e in viewDidLoad)
    SKProductsRequest *productRequest =
    [[SKProductsRequest alloc] initWithProductIdentifiers:@"2"];
    productRequest.delegate = self;
    [productRequest start];



    NSSet *productIdentifiersForPurchase = [NSSet setWithObject:@"2"];

    [[PlanIAPHelper sharedInstance] buyProduct:product];
}

The last line has a syntax error because it doesn't know what the product variable is because I didn't declare it. And that is my problem. I am not sure how to construct this object so that it gets purchased.

Would anyone be able to help me to get this to work correctly? What is the right way to make this call?

Upvotes: 0

Views: 68

Answers (1)

Joel Bell
Joel Bell

Reputation: 2718

Its a bit more involved than that. I would recommend reading the In-App Purchase Programming Guide if you haven't already it can be a bit tricky to get working right.

https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction.html

Basically you need to request the SKProducts from Apple by their identifiers. They send you the SKProduct then you use that SKProduct for the purchase. The code looks something like this.

NSSet *identifiers = [NSSet setWithObjects:@"my_product_identifier1", @"my_product_identifier_2", nil];
SKProductRequest *request = [[SKProductRequest alloc] iniWithProductIdentifiers:identifiers];
request.delegate = self;
[request start];

Then you should get a callback from the delegate method like this with the SKProducts that you requested

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductResponse *)response {

    NSArray *products = response.products;
    SKProduct *product = [products firstObject];
   [[PlanIAPHelper sharedInstance] buyProduct:product];
}

Please excuse any mistakes, I hand-wrote this. Let me know if you have any trouble.

I've also used CargoBay https://github.com/mattt/CargoBay which is an open source wrapper around the In app purchase Framework. Makes working with IAP's much easier and also makes it super easy to validate purchases from the device which is really handy.

Upvotes: 2

Related Questions