Реализация покупки в приложении и ее восстановление в iphone

Я реализовал покупку приложения в одном из моих приложений с помощью MKStoreManager. Теперь у Apple есть новое руководство, согласно которому, если вы делаете покупку приложения, вы должны предоставить пользователю возможность восстановления уже купленного приложения. Итак, я сделал Этот метод вызывается при нажатии кнопки "восстановить".

- (void) checkPurchasedItems
{
   [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; 
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

и отсюда этот метод запускается

- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
    {
     NSMutableArray* purchasableObjects  = [[NSMutableArray alloc] init];

        NSLog(@"received restored transactions: %i", queue.transactions.count);
        for (SKPaymentTransaction *transaction in queue.transactions)
        {
            NSString *productID = transaction.payment.productIdentifier;
            [purchasableObjects addObject:productID];
        }

    }

Но теперь у меня есть сомнения, как я могу проверить, работает ли реставрация или нет. Может ли кто-нибудь помочь мне заранее. Спасибо.


person iOS Developer    schedule 03.07.2012    source источник
comment
Вы можете проверить это, создав тестового пользователя в itunesConnect. Купите приложение с помощью тестового пользователя, удалите приложение и проверьте, работает ли восстановление.   -  person Sumanth    schedule 03.07.2012
comment
@Sumanth Я создал для этого учетную запись песочницы. Могу ли я узнать, что код, который я использовал, правильный или нет для восстановления?   -  person iOS Developer    schedule 03.07.2012
comment
И при тестировании с учетной записью песочницы, которую я создал, я получаю это предупреждение. У этой учетной записи нет разрешения на совершение покупок в приложениях. Вы можете изменить разрешения учетной записи в iTunes Connect.   -  person iOS Developer    schedule 03.07.2012
comment
Да, это был правильный код для восстановления покупки. Во-вторых, не могли бы вы показать мне снимок экрана с предупреждением?   -  person Sumanth    schedule 03.07.2012
comment
@Sumanth, я исправил это, изменив местоположение на США. И теперь он начинает загрузку. Но не загружается. И когда я снова пытаюсь загрузить, я получаю предупреждение, как на скрине. И даже после нажатия ОК , он не загружается. Снимок экрана прилагается.   -  person iOS Developer    schedule 03.07.2012
comment
Да, это произойдет, потому что вы ранее покупали свое приложение, поэтому в нем говорилось, что вы уже купили. Здесь вы не восстанавливаете предыдущую транзакцию [[SKPaymentQueue defaultQueue] addTransactionObserver: self]; [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; Вам нужно позвонить в эти две линии.   -  person Sumanth    schedule 03.07.2012
comment
позвольте нам продолжить это обсуждение в чате   -  person Sumanth    schedule 03.07.2012
comment
У меня такая же проблема: у этой учетной записи нет разрешения на совершение покупок в приложении. Вы можете изменить разрешения учетной записи в iTunes Connect.   -  person phil88530    schedule 20.09.2012


Ответы (1)


Вот как вы реализуете Реставрацию

- (void)loadStore
{
// restarts any purchases if they were interrupted last time the app was open
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];

// get the product description (defined in early sections)
[self requestProUpgradeProductData];
}

- (void)requestProUpgradeProductData
{
NSSet *productIdentifiers = [NSSet setWithObject:kInAppPurchaseProUpgradeProductId];
productsRequest = [[SKProductsRequest alloc]     initWithProductIdentifiers:productIdentifiers];
productsRequest.delegate = self;
[productsRequest start];

// we will release the request object in the delegate callback
}

После этого он вызовет этот метод

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSArray *products = response.products;
proUpgradeProduct = [products count] == 1 ? [[products objectAtIndex:0] retain] : nil;
if (proUpgradeProduct)
{
NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
NSLog(@"Product price: %@" , proUpgradeProduct.price);
NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
if ([self canMakePurchases]) {
    if ([self respondsToSelector:@selector(purchaseProUpgrade)]) {
        [self purchaseProUpgrade];
    }
}
else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[self languageSelectedStringForKey:@"Error"] message:@"Cannot connect to Store.\n Please Enable the Buying in settings" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}
}

for (NSString *invalidProductId in response.invalidProductIdentifiers)
{
[SVProgressHUD dismiss];
[cancelButton setEnabled:YES];
[buyNowButton setEnabled:YES];
[restoreButton setEnabled:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Error occured" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
NSLog(@"Invalid product id: %@" , invalidProductId);
}

// finally release the reqest we alloc/init’ed in requestProUpgradeProductData
[productsRequest release];
[[NSNotificationCenter defaultCenter]         postNotificationName:kInAppPurchaseManagerProductsFetchedNotification object:self userInfo:nil];
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
[self recordTransaction:transaction];
[self provideContent:transaction.payment.productIdentifier];
[self finishTransaction:transaction wasSuccessful:YES];
}
- (void)purchaseProUpgrade
{
[SVProgressHUD showInView:self.view status:[self languageSelectedStringForKey:@"Connecting Store"] networkIndicator:YES];
SKPayment *payment = [SKPayment     paymentWithProductIdentifier:kInAppPurchaseProUpgradeProductId];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)recordTransaction:(SKPaymentTransaction *)transaction
{
if ([transaction.payment.productIdentifier isEqualToString:kInAppPurchaseProUpgradeProductId])
{
// save the transaction receipt to disk
[[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@"proUpgradeTransactionReceipt" ];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}

Наконец этот метод

- (void)finishTransaction:(SKPaymentTransaction *)transaction wasSuccessful:        (BOOL)wasSuccessful
{
// remove the transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];

NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:transaction, @"transaction" , nil];
if (wasSuccessful)
{
//Write your transaction complete statement required for your project
}
person Sumanth    schedule 03.07.2012