2014-01-09 126 views
0

我已將In App Purchase編入我的應用並使其工作,以便用戶可通過按按鈕進行購買。如何將「恢復購買」方法添加到我的應用內購買

我現在想爲用戶創建一個按鈕,以便能夠恢復購買。我正在'UpgradeViewController'中使用共享實例從'IAHelper.h'中檢索方法,因此我已經顯示了這兩個代碼段有助於幫助

如何在In App Purchase中添加'Restore Purchase'方法?

IAHelper.m

#import "IAPHelper.h" 

// Add to top of file 
NSString *const IAPHelperProductPurchasedNotification = @"IAPHelperProductPurchasedNotification"; 

@implementation IAPHelper 
{ 
    // 3 
    SKProductsRequest * _productsRequest; 
    // 4 
    RequestProductsCompletionHandler _completionHandler; 
    NSSet * _productIdentifiers; 
    NSMutableSet * _purchasedProductIdentifiers; 

     NSArray *_products; 

} 

- (id)initWithProductIdentifiers:(NSSet *)productIdentifiers { 

    if ((self = [super init])) { 

     // Store product identifiers 
     _productIdentifiers = productIdentifiers; 

     // Check for previously purchased products 
     _purchasedProductIdentifiers = [NSMutableSet set]; 
     for (NSString * productIdentifier in _productIdentifiers) { 
      BOOL productPurchased = [[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier]; 
      if (productPurchased) { 
       [_purchasedProductIdentifiers addObject:productIdentifier]; 
       NSLog(@"Previously purchased: %@", productIdentifier); 
      } else { 
       NSLog(@"Not purchased: %@", productIdentifier); 
      } 
     } 

     [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; 

    } 
    return self; 
} 

- (void)requestProductsWithCompletionHandler:(RequestProductsCompletionHandler)completionHandler { 

    // 1 
    _completionHandler = [completionHandler copy]; 

    // 2 
    _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:_productIdentifiers]; 
    _productsRequest.delegate = self; 
    [_productsRequest start]; 

} 


#pragma mark - SKProductsRequestDelegate 

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

    NSLog(@"Loaded list of products... %@", response.products); 
    _productsRequest = nil; 



    NSArray * skProducts = response.products; 
    for (SKProduct * skProduct in skProducts) { 
     NSLog(@"Found product: %@ %@ %0.2f", 
       skProduct.productIdentifier, 
       skProduct.localizedTitle, 
       skProduct.price.floatValue); 
    } 

    _completionHandler(YES, skProducts); 
    _completionHandler = nil; 

} 

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error { 

    NSLog(@"Failed to load list of products."); 
    _productsRequest = nil; 

    _completionHandler(NO, nil); 
    _completionHandler = nil; 

} 


- (BOOL)productPurchased:(NSString *)productIdentifier { 
    return [_purchasedProductIdentifiers containsObject:productIdentifier]; 
} 

- (void)buyProduct:(SKProduct *)product { 

    NSLog(@"Buying %@...", product.productIdentifier); 

    SKPayment * payment = [SKPayment paymentWithProduct:product]; 
    [[SKPaymentQueue defaultQueue] addPayment:payment]; 

} 

- (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(@"completeTransaction..."); 

    [self provideContentForProductIdentifier:transaction.payment.productIdentifier]; 
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; 
} 

- (void)restoreTransaction:(SKPaymentTransaction *)transaction { 
    NSLog(@"restoreTransaction..."); 

    [self provideContentForProductIdentifier:transaction.originalTransaction.payment.productIdentifier]; 
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; 
} 

- (void)failedTransaction:(SKPaymentTransaction *)transaction { 

    NSLog(@"failedTransaction..."); 
    if (transaction.error.code != SKErrorPaymentCancelled) 
    { 
     NSLog(@"Transaction error: %@", transaction.error.localizedDescription); 
    } 

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction]; 
} 

// Add new method 
- (void)provideContentForProductIdentifier:(NSString *)productIdentifier { 

    [_purchasedProductIdentifiers addObject:productIdentifier]; 
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
    [[NSNotificationCenter defaultCenter] postNotificationName:IAPHelperProductPurchasedNotification object:productIdentifier userInfo:nil]; 

} 

- (NSArray*)getProductArrray { 

    return _products; 

} 

@end 

UpgradeViewController

#import "UpgradeViewController.h" 
#import "ECSlidingViewController.h" 
#import "MenuViewController.h" 



#import "RageIAPHelper.h" 
#import <StoreKit/StoreKit.h> 

@interface UpgradeViewController() 

{ 
    NSMutableArray *_objects; 

    NSArray *_products; 

    NSNumberFormatter * _priceFormatter; 


} 


@property (retain, nonatomic) IBOutlet JSAnimatedImagesView *animatedImagesView; 
@property (assign, nonatomic) IBOutlet UIButton *installFullAppButton; 
@end 

@implementation UpgradeViewController 
@synthesize menuBtn, animatedImagesView = _animatedImagesView, scrolly, bannerView, labelPrice; 


- (void)awakeFromNib 
{ 
    [super awakeFromNib]; 
} 



- (NSString *)publisherIdForAdSdkBannerView:(AdSdkBannerView *)banner { 
    return @"e0616d4190bff65279ed5c20de1b5653"; 
} 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [RageIAPHelper sharedInstance]; 

    _products = nil; 

    [[RageIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *products) { 
     if (success) { 
      _products = products; 

     } 
    }]; 



    // Price New 



    SKProduct * product = (SKProduct *) [_products objectAtIndex:0]; 


    ([[RageIAPHelper sharedInstance] productPurchased:product.productIdentifier]); 


     // Unlock your features code comes here 

     UIButton *buyButton = [[UIButton alloc] initWithFrame:CGRectMake(-1, 370, 320, 60)]; 
     UIImage *btnImage = [UIImage imageNamed:@"upgrade-new.png"]; 
     [buyButton setImage:btnImage forState:UIControlStateNormal]; 
     [buyButton.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0]]; 
     [buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
     [buyButton.titleLabel setShadowColor:[UIColor colorWithWhite:0.1 alpha:1.0]]; 
     [buyButton.titleLabel setShadowOffset:CGSizeMake(0, -1)]; 
     [buyButton addTarget:self action:@selector(buyButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; 
     buyButton.tag = 0; 
     [[self view] addSubview:buyButton]; 




    // Purchase Action End 


    [super viewDidLoad]; 


    _priceFormatter = [[NSNumberFormatter alloc] init]; 
    [_priceFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; 
    [_priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 
    [_priceFormatter setLocale:product.priceLocale]; 
    labelPrice.text = [_priceFormatter stringFromNumber:product.price]; 




    self.view.layer.shadowOpacity = 0.75f; 
    self.view.layer.shadowRadius = 10.0f; 
    self.view.layer.shadowColor = [UIColor blackColor].CGColor; 


    if (![self.slidingViewController.underLeftViewController isKindOfClass:[MenuViewController class]]) { 
     self.slidingViewController.underLeftViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"Menu"]; 
    } 


    [self.view addGestureRecognizer:self.slidingViewController.panGesture]; 

    self.menuBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    menuBtn.frame = CGRectMake(8, 30, 34, 24); 
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"menuButton.png"] forState:UIControlStateNormal]; 
    [menuBtn addTarget:self action:@selector(revealMenu:) forControlEvents:UIControlEventTouchUpInside]; 


    [self.view addSubview:self.menuBtn]; 


    myWebView.opaque = NO; 
    myWebView.backgroundColor = [UIColor clearColor]; 

} 






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

- (IBAction)revealMenu:(id)sender 
{ 
    [self.slidingViewController anchorTopViewTo:ECRight]; 
} 

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
    self.screenName = @"Upgrade"; 
} 



#pragma mark - UI 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
{ 
    return (toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 




- (void)buyButtonTapped:(id)sender { 

    UIButton *buyButton = (UIButton *)sender; 
    SKProduct *product = [_products objectAtIndex:buyButton.tag]; 

    NSLog(@"Buying %@...", product.productIdentifier); 
    [[RageIAPHelper sharedInstance] buyProduct:product]; 

} 








@end 
+0

你沒有問一個問題... – Wain

回答

1

蘋果會拒絕你的應用程序,如果你沒有一個按鈕來做到這一點,那麼,他們幫了我,即使他們認可該應用程序在後臺自動檢查。

任何方式,如果你添加到你的幫手;

- (void)restoreCompletedTransactions 
{ 
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; 
} 

並從VC調用這樣的;

- (IBAction)restoreAction:(id)sender 
{ 

    [[RageIAPHelper sharedInstance] restoreCompletedTransactions]; 

} 
+0

@Omar此外,在IAPhelper你didRecieveResponse您需要更改的最後幾行檢查完成處理程序,以這樣或崩潰一些時間。 if(_completionHandler){_ completionHandler(YES,skProducts);} _ completionHandler = nil; –

+0

謝謝,didReceiveResponse中代碼的含義是什麼? – Omar

+0

這是三行,它基本上測試_completionHandler存在之前它試圖設置它(我認爲重複按購買,重新存儲按鈕可以導致它在這一點,當它不被創建)。它將替換該方法中的最後兩行。我會顯示爲另一個答案。 –

0

當你有這樣的;

- (void)restoreCompletedTransactions 
{ 
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; 
} 

並從VC調用這樣的;

- (IBAction)restoreAction:(id)sender 
{ 

    [[RageIAPHelper sharedInstance] restoreCompletedTransactions]; 

} 

此方法需要更改爲此;

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

    NSLog(@"Loaded list of products... %@", response.products); 
    _productsRequest = nil; 



    NSArray * skProducts = response.products; 
    for (SKProduct * skProduct in skProducts) { 
     NSLog(@"Found product: %@ %@ %0.2f", 
       skProduct.productIdentifier, 
       skProduct.localizedTitle, 
       skProduct.price.floatValue); 
    } 

// Check is the Handler exists 
if(_completionHandler) 
{ 
    _completionHandler(YES, skProducts); 
} 
_completionHandler = nil; 

}