IOS應用程式內購買


IOS應用程式內購買


簡介

應用程式內購買是應用程式用於購買額外內容或升級功能。

實例步驟

1.在iTunes 連線中請確保擁有一個唯一的App ID(unique App ID ),當建立捆綁的ID( bundle ID)應用程式更新時,程式碼會以對應的設定檔簽署在Xcode上

2.建立新的應用程式和更新應用程式資訊。你可以知道更多有關的,在蘋果的添加新的應用程式文件中

3.在應用程式頁的管理應用程式( Manage In-App Purchase)中,為app內付費添加新產品

4.確保設定的應用程式為的銀行詳細。需要將其設定為在應用程式內購買(In-App purchase)。此外在 iTunes 中使用管理使用者(Manage Users)選項,建立一個測試使用者帳戶連接您的應用程式的頁面。

5.下一步是與處理程式碼和為我們在應用程式內購買創建有關的 UI。

6.建立一個單一的視圖應用程序,並在iTunes 中指定的標識符連接輸入捆綁標識符

7.更新ViewController.xib ,如下所示

InAppPurchase_OutputInterface

#8.為三個標籤建立IBOutlets,且將按鈕分別命名為productTitleLabel、 productDescriptionLabel、 productPriceLabel 和purchaseButton

9.選擇專案文件,然後選擇目標,然後新增StoreKit.framework

10.更新ViewController.h ,如下所示

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

@interface ViewController : UIViewController<
SKProductsRequestDelegate,SKPaymentTransactionObserver>
{
    SKProductsRequest *productsRequest;
    NSArray *validProducts;
    UIActivityIndicatorView *activityIndicatorView;
    IBOutlet UILabel *productTitleLabel;
    IBOutlet UILabel *productDescriptionLabel;
    IBOutlet UILabel *productPriceLabel;
    IBOutlet UIButton *purchaseButton;
}
- (void)fetchAvailableProducts;
- (BOOL)canMakePurchases;
- (void)purchaseMyProduct:(SKProduct*)product;
- (IBAction)purchase:(id)sender;

@end

11.更新ViewController.m ,如下所示

#import "ViewController.h"
#define kTutorialPointProductID 
@"com.tutorialPoints.testApp.testProduct"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Adding activity indicator
    activityIndicatorView = [[UIActivityIndicatorView alloc]
    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatorView.center = self.view.center;
    [activityIndicatorView hidesWhenStopped];
    [self.view addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];
    //Hide purchase button initially
    purchaseButton.hidden = YES;
    [self fetchAvailableProducts];    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)fetchAvailableProducts{
    NSSet *productIdentifiers = [NSSet 
    setWithObjects:kTutorialPointProductID,nil];
    productsRequest = [[SKProductsRequest alloc] 
    initWithProductIdentifiers:productIdentifiers];
    productsRequest.delegate = self;
    [productsRequest start];
}

- (BOOL)canMakePurchases
{
    return [SKPaymentQueue canMakePayments];
}
- (void)purchaseMyProduct:(SKProduct*)product{
    if ([self canMakePurchases]) {
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
    else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
        @"Purchases are disabled in your device" message:nil delegate:
        self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alertView show];
    }
}
-(IBAction)purchase:(id)sender{
    [self purchaseMyProduct:[validProducts objectAtIndex:0]];
    purchaseButton.enabled = NO; 
}

#pragma mark StoreKit Delegate

-(void)paymentQueue:(SKPaymentQueue *)queue 
 updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                    NSLog(@"Purchasing");
                break;                
            case SKPaymentTransactionStatePurchased:
               if ([transaction.payment.productIdentifier 
                  isEqualToString:kTutorialPointProductID]) {
                   NSLog(@"Purchased ");
                   UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                   @"Purchase is completed succesfully" message:nil delegate:
                   self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                   [alertView show];
                }               
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;                
            case SKPaymentTransactionStateRestored:               
                NSLog(@"Restored ");               
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;                
            case SKPaymentTransactionStateFailed:
                NSLog(@"Purchase failed ");
                break;
            default:
                break;
        }
    }
}

-(void)productsRequest:(SKProductsRequest *)request 
 didReceiveResponse:(SKProductsResponse *)response
{
    SKProduct *validProduct = nil;
    int count = [response.products count];
    if (count>0) {
        validProducts = response.products;
        validProduct = [response.products objectAtIndex:0];
        if ([validProduct.productIdentifier 
           isEqualToString:kTutorialPointProductID]) {
            [productTitleLabel setText:[NSString stringWithFormat:
            @"Product Title: %@",validProduct.localizedTitle]];
            [productDescriptionLabel setText:[NSString stringWithFormat:
            @"Product Desc: %@",validProduct.localizedDescription]];
            [productPriceLabel setText:[NSString stringWithFormat:
            @"Product Price: %@",validProduct.price]];           
        }        
    } else {
        UIAlertView *tmp = [[UIAlertView alloc]
                            initWithTitle:@"Not Available"
                            message:@"No products to purchase"
                            delegate:self
                            cancelButtonTitle:nil
                            otherButtonTitles:@"Ok", nil];
        [tmp show];
    }    
    [activityIndicatorView stopAnimating];
    purchaseButton.hidden = NO;
}

@end

#注意:需要修改你創建In-App Pur(應用程式內購買)的kTutorialPointProductID 。透過修改fetchAvailableProducts產品識別碼的 NSSet, 你可以新增多個產品。

輸出

執行該應用程式,輸出結果如下

InAppPurchase_Output1

#確保已中登入。點選購買選擇現有的Apple ID。輸入有效的測試帳戶的使用者名稱和密碼。幾秒鐘後,顯示下面的資訊

InAppPurchase_Output2

#一旦產品成功購買,將獲得以下資訊。可以在顯示此資訊的地方,更新應用程式功能相關的程式碼

InAppPurchase_Output3

#