2014-09-16 3 views
0

Я следил за this tutorial, чтобы помочь мне добавить покупки в приложении. Он работает хорошо, но теперь я пытаюсь добавить еще один неиспользуемый IAP. Я определил свой второй идентификатор продукта и создал метод для кнопки покупки, но я не уверен, что мне нужно создать еще один SKProductsRequest для этого дополнительного элемента, или если я использую тот же самый и т. Д.Добавление дополнительных покупок в приложении

Здесь мой полный код.

#define kRemoveAdsProductIdentifier @"099" 
#define kDoubleEarningRateProductIdentifer @"199" 

- (void)removeAds{ 
    NSLog(@"User requests to remove ads"); 

    if([SKPaymentQueue canMakePayments]){ 
     NSLog(@"User can make payments"); 

     SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kRemoveAdsProductIdentifier]]; 
     productsRequest.delegate = self; 
     [productsRequest start]; 

    } 
    else{ 
     NSLog(@"User cannot make payments due to parental controls"); 
     //this is called the user cannot make payments, most likely due to parental controls 
    } 
} 

- (void)doubleEarningRate{ 
    NSLog(@"User requests 2x earning rate"); 

    if([SKPaymentQueue canMakePayments]){ 
     NSLog(@"User can make payments"); 

     SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kDoubleEarningRateProductIdentifer]]; 
     productsRequest.delegate = self; 
     [productsRequest start]; 

    } 
    else{ 
     NSLog(@"User cannot make payments due to parental controls"); 
     //this is called the user cannot make payments, most likely due to parental controls 
    } 
} 

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{ 
    SKProduct *validProduct = nil; 
    int count = [response.products count]; 
    if(count > 0){ 
     validProduct = [response.products objectAtIndex:0]; 
     NSLog(@"Products Available!"); 
     [self purchase:validProduct]; 
    } 
    else if(!validProduct){ 
     NSLog(@"No products available"); 
     //this is called if your product id is not valid, this shouldn't be called unless that happens. 
    } 
} 

- (void)purchase:(SKProduct *)product{ 
    SKPayment *payment = [SKPayment paymentWithProduct:product]; 
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; 
    [[SKPaymentQueue defaultQueue] addPayment:payment]; 
} 

- (void) restore{ 
    //this is called when the user restores purchases, you should hook this up to a button 
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; 
} 

- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue 
{ 
    NSLog(@"received restored transactions: %i", queue.transactions.count); 
    for (SKPaymentTransaction *transaction in queue.transactions) 
    { 
     if(SKPaymentTransactionStateRestored){ 
      NSLog(@"Transaction state -> Restored"); 
      //called when the user successfully restores a purchase 
      [self doRemoveAds]; 
      [self doubleEarningRate]; 
      [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; 
      break; 
     } 

    } 

} 

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{ 
    for(SKPaymentTransaction *transaction in transactions){ 
     switch (transaction.transactionState){ 
      case SKPaymentTransactionStatePurchasing: NSLog(@"Transaction state -> Purchasing"); 
       //called when the user is in the process of purchasing, do not add any of your own code here. 
       break; 
      case SKPaymentTransactionStatePurchased: 
       //this is called when the user has successfully purchased the package (Cha-Ching!) 

       [self doRemoveAds]; //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads 
       [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; 
       NSLog(@"Transaction state -> Purchased"); 
       break; 
      case SKPaymentTransactionStateRestored: 
       NSLog(@"Transaction state -> Restored"); 
       //add the same code as you did from SKPaymentTransactionStatePurchased here 
       [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; 
       break; 
      case SKPaymentTransactionStateFailed: 
       //called when the transaction does not finnish 
       if(transaction.error.code != SKErrorPaymentCancelled){ 
        NSLog(@"Transaction state -> Cancelled"); 
        //the user cancelled the payment ;(
       } 
       [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; 
       break; 
     } 
    } 
} 



-(void)doRemoveAds 
{ 
    areAdsRemoved = true; 
    NSLog(@"Ads Removed"); 
    [topBanner removeFromSuperview]; 
} 

-(void)doDoubleEarningRate 
{ 

} 

Я также прочитал яблочного документации, объяснил мне, что делает каждая часть, но я все еще невежественный о том, как я могу добавить еще одну покупку, и большинство других учебников сделаны по-разному или устарели. Также все переменные и косвенность немного запугивают меня. Поэтому я надеюсь, что кто-то может дать мне быстрый шаг за шагом, чтобы добавить другую покупку.

Чтобы сделать его более понятным, этот подход идеально подходит только для покупки приложения. Однако я не знаю, как добавить больше, так как я не знаю, как заставить программу распознавать, какая покупка в приложении выбирается.

Спасибо.

ответ

0

Я исправил это, создав метод под названием provideContent:(NSString *)productId. Затем вы можете использовать оператор switch или оператор if, чтобы различать идентификаторы продукта. Нет необходимости создавать несколько типов методов productRequest и т. Д.

Смежные вопросы