IOS IAP Tutorials

Source: Internet
Author: User
Tags uikit

1. Create an app

First go to itunes Connect and press Manage Your applications


Next press Add New Applicationbutton to create the app

2. Create an IAP in your app


After creating the app, in the Manage Your Applications app icon, go to the app

You will see the screen click Manage in App purchases to access the IAP management screen

Notice the bundle ID on the left side, and in the Xcode project, the settings in Info.plist need to be the same as this bundle

(This bundle ID will be populated when the app is created)

This is the management screen for IAP, just press create Newbutton to create an IAP

In this image I've created three IAP.

The Product ID is the only product ID that can be used to request information about the IAP and the transaction

Consumable

consumables, each download is charged

Non-consumable

One-time payment, often used in the upgrade Pro version or remove ads, etc.

auto-renewable Subscriptions

Update your subscription on your own initiative

Free Subscription

Free Subscription

Non-renewing Subscription

Non-Update your subscription on your own initiative

3. How to create a sandbox test user

Go to itunes Connect and click Manage Users

At the midpoint of this screen, test User

Press Add New user to be able ,Email address is log in sandbox test username

The password part can be created by itself when the add New user

4. Code

/* * CBiOSStoreManager.h * CloudBox cross-platform Framework Project * * Created by Cloud on 2012/10/30. * Copyright: Cloud Hsu. All rights reserved. * */#import <UIKit/UIKit.h> #import <StoreKit/StoreKit.h> @interface cbiosstoremanager:nsobject< skproductsrequestdelegate,skpaymenttransactionobserver>{nsstring* _buyproductidtag;} + (cbiosstoremanager*) sharedinstance;-(void) Buy: (nsstring*) buyproductidtag;-(bool) canmakepay;-(void) initialstore;-(void) releasestore;-(void) Requestproductdata: (nsstring*) buyproductidtag;-(void) Providecontent: ( NSString *) product;-(void) Recordtransaction: (NSString *) product;-(void) Requestproupgradeproductdata: (NSString*) buyproductidtag;-(void) Paymentqueue: (Skpaymentqueue *) queue updatedtransactions: (Nsarray *) transactions;-(void) Purchasedtransaction: (Skpaymenttransaction *) transaction;-(void) Completetransaction: (Skpaymenttransaction *) transaction;-(void) Failedtransaction: (skpaymenttransaction *) transaction;-(void) paymentqueuerestorecompletedtransactionsfinished: (Skpaymenttransaction *) transaction;-(void) Paymentqueue: (Skpaymentqueue *) paymentqueue restorecompletedtransactionsfailedwitherror: (NSError *) error;-(void) Restoretransaction: (skpaymenttransaction *) transaction; @end

/* * CBIOSSTOREMANAGER.MM * CloudBox cross-platform Framework Project * * Created by Cloud on 2012/10/30. * Copyright: Cloud Hsu. All rights reserved. * */#import "CBiOSStoreManager.h" @implementation cbiosstoremanagerstatic cbiosstoremanager* _sharedinstance = nil;+ ( cbiosstoremanager*) sharedinstance{@synchronized ([Cbiosstoremanager class]) {if (!_sharedinstance) [[Self alloc] Init        ]; return _sharedinstance;} return nil;} + (ID) alloc{@synchronized ([Cbiosstoremanager class]) {Nsassert (_sharedinstance = = nil, @ "attempted to allocate a second Instance of a singleton.\n "); _sharedinstance = [Super Alloc];return _sharedinstance;} return nil;} -(ID) init {self = [super init];if (self! = nil) {//initialize stuff Here}return self;} -(void) initialstore{[[Skpaymentqueue Defaultqueue] addtransactionobserver:self];} -(void) releasestore{[[Skpaymentqueue Defaultqueue] removetransactionobserver:self];} -(void) Buy: (nsstring*) buyproductidtag{[self requestproductdata:buyproductidtag];} -(BooL) canmakepay{return [Skpaymentqueue canmakepayments];} -(void) Requestproductdata: (nsstring*) buyproductidtag{NSLog (@ "---------Request product information------------\ n"    );    _buyproductidtag = [Buyproductidtag retain];    Nsarray *product = [[Nsarray alloc] initwithobjects:buyproductidtag,nil];    Nsset *nsset = [Nsset setwitharray:product];    Skproductsrequest *request=[[skproductsrequest alloc] initwithproductidentifiers:nsset];    request.delegate=self;    [Request start]; [Product release];} -(void) Productsrequest: (skproductsrequest *) Request Didreceiveresponse: (Skproductsresponse *) response{NSLog (@ "    -----------Getting product information--------------\ n ");    Nsarray *myproduct = response.products;    NSLog (@ "Product id:%@\n", response.invalidproductidentifiers);    NSLog (@ "Product count:%d\n", [myproduct Count]);        Populate UI for (skproduct *product in myproduct) {NSLog (@ "Detail product info\n"); NSLog (@ "skproduct Description:%@\n", [Product Description]);        NSLog (@ "Product localized title:%@\n", product.localizedtitle);        NSLog (@ "Product localized descitption:%@\n", product.localizeddescription);        NSLog (@ "Product Price:%@\n", Product.price);    NSLog (@ "Product identifier:%@\n", product.productidentifier);    } skpayment *payment = nil;    Payment = [Skpayment paymentwithproduct:[response.products objectatindex:0]];    NSLog (@ "---------Request payment------------\ n");    [[Skpaymentqueue Defaultqueue] addpayment:payment];        [Request Autorelease]; }-(void) Requestproupgradeproductdata: (nsstring*) buyproductidtag{NSLog (@ "------Request to upgrade product    Data---------\ n ");    Nsset *productidentifiers = [Nsset Setwithobject:buyproductidtag];    skproductsrequest* productsrequest = [[Skproductsrequest alloc] initwithproductidentifiers:productidentifiers];    Productsrequest.delegate = self;        [Productsrequest start]; }-(void) Request: (Skrequest *) Request DidfailwitherroR: (Nserror *) error{NSLog (@ "-------Show fail message----------\ n"); Uialertview *alerview = [[Uialertview alloc] initwithtitle:nslocalizedstring (@ "Alert", NULL) message:[error Localizeddescription] Delegate:nil Cancelbuttontitle:nslocalizedstri    Ng (@ "Close", nil) otherbuttontitles:nil];    [Alerview show];   [Alerview release];}    -(void) Requestdidfinish: (Skrequest *) request{NSLog (@ "----------request finished--------------\ n");    }-(void) Purchasedtransaction: (skpaymenttransaction *) transaction{NSLog (@ "-----purchased transaction----\ n");    Nsarray *transactions =[[nsarray alloc] initwithobjects:transaction, nil];    [Self paymentqueue:[skpaymentqueue defaultqueue] updatedtransactions:transactions];    [Transactions release];} -(void) Paymentqueue: (Skpaymentqueue *) queue updatedtransactions: (Nsarray *) transactions{NSLog (@ "-----Payment    Result--------\ n "); For (Skpaymenttransaction *transaction in TransactiONS) {switch (transaction.transactionstate) {case skpaymenttransactionstatepurchased:                [Self completetransaction:transaction];                NSLog (@ "-----Transaction purchased--------\ n");                                                              Uialertview *alerview = [[Uialertview alloc] initwithtitle:@ "congratulation"                                                              message:@ "Transaction suceed!"                                   Delegate:nil cancelbuttontitle:nslocalizedstring (@ "Close", nil) otherbuttontitles:nil];                [Alerview show];                [Alerview release];            Break                Case skpaymenttransactionstatefailed: [Self failedtransaction:transaction];                NSLog (@ "-----Transaction Failed--------\ n");                                                               Uialertview *alerview2 = [[Uialertview alloc] initwithtitle:@ "Failed" message:@ "Sorry, your transcation failed, try again. "                                   Delegate:nil cancelbuttontitle:nslocalizedstring (@ "Close", nil) otherbuttontitles:nil];                [AlerView2 show];                [AlerView2 release];            Break                Case skpaymenttransactionstaterestored: [Self restoretransaction:transaction];            NSLog (@ "-----already buy this product--------\ n");                Case Skpaymenttransactionstatepurchasing:nslog (@ "-----transcation puchasing--------\ n");            Break        Default:break; }}}-(void) Completetransaction: (skpaymenttransaction *) transaction {NSLog (@ "-----completetransaction--------\ n    ");    Your application should implement these, methods.    NSString *product = Transaction.payment.productIdentifier; if ([Product length] > 0) {nsarray *TT = [Product Componentsseparatedbystring:@ "."];        NSString *bookid = [TT Lastobject];            if ([bookid length] > 0) {[Self recordtransaction:bookid];        [Self providecontent:bookid];       }}//Remove the transaction from the payment queue.       [[Skpaymentqueue Defaultqueue] finishtransaction:transaction];    }-(void) Recordtransaction: (NSString *) product{NSLog (@ "-----Record transcation--------\ n");   Todo:maybe want to save transaction result into plist.}   -(void) Providecontent: (NSString *) product{NSLog (@ "-----Download product content--------\ n");}    -(void) Failedtransaction: (skpaymenttransaction *) transaction{NSLog (@ "failed\n"); if (transaction.error.code! = skerrorpaymentcancelled) {} [[Skpaymentqueue Defaultqueue] Finishtransaction:tran Saction];} -(void) paymentqueuerestorecompletedtransactionsfinished: (skpaymenttransaction *) transaction{}-(void) RestoreTran Saction: (skpaymenttransaction *) transaction{NSLog (@ "-----Restore transaction--------\ n ");}    -(void) Paymentqueue: (Skpaymentqueue *) paymentqueue restorecompletedtransactionsfailedwitherror: (NSError *) error{ NSLog (@ "-------Payment Queue----\ n");} #pragma mark connection delegate-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{NSLog ( @ "%@\n", [[[NSString Alloc] initwithdata:data encoding:nsutf8stringencoding] autorelease]);} -(void) connectiondidfinishloading: (Nsurlconnection *) connection{}-(void) connection: (Nsurlconnection *) connecti        On Didreceiveresponse: (nsurlresponse *) response{switch ([(nshttpurlresponse *) Response StatusCode]) {case 200:        Case 206:break;        Case 304:break;        Case 400:break;        Case 404:break;        Case 416:break;        Case 403:break;        Case 401:case 500:break;    Default:break; }}-(void) connection: (Nsurlconnection *) connectiOn Didfailwitherror: (Nserror *) error{NSLog (@ "test\n");} -(void) dealloc{[super Dealloc];} @end


[[Skpaymentqueue Defaultqueue] addtransactionobserver:self];
since the transaction is permanently valid, it is recommended thatthe Addtrans actionobserver this to be monitored when the app is started, rather than listening when the user wants to buy something .

-(void) Paymentqueue: (Skpaymentqueue *) queue updatedtransactions: (Nsarray *) transactions
The trading results are shown here

Apple to prepare sandbox test environment for a period of time, if you create an IAP to get information, but can not be successful trading, you have to wait a moment

In addition, if the simulator can buy, but the real machine purchase failed, do hard reset will be able to, always hold the home button and the power button to be able to do hard reset

Press and hold will appear the shutdown screen, do not ignore it, continue to wait until the white Apple appears, you can release and so on when it re-boot completed and then test

5. IAP Operation Flowchart

6. Sample Download

Download link

IOS IAP Tutorials

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.