购买失败处理
- 监听购买结果:通过实现
SKPaymentTransactionObserver
协议的 paymentQueue:updatedTransactions:
方法来监听交易状态。
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStateFailed:
// 处理购买失败
if (transaction.error.code == SKErrorPaymentCancelled) {
// 用户取消购买
NSLog(@"用户取消购买");
} else {
// 其他失败原因
NSLog(@"购买失败: %@", transaction.error.localizedDescription);
}
// 完成交易
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
// 其他状态处理
case SKPaymentTransactionStatePurchased:
case SKPaymentTransactionStateRestored:
case SKPaymentTransactionStateDeferred:
break;
}
}
}
- 向用户提示:根据失败原因弹出友好的提示框,告知用户失败原因,例如使用
UIAlertController
。
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"购买失败" message:@"您的购买操作未能完成,请检查网络或重试。" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
网络异常处理
- 请求前检测网络:在发起购买请求前,使用
Reachability
等工具检测网络状态。
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
if (networkStatus == NotReachable) {
// 提示用户网络不可用
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"网络异常" message:@"当前网络不可用,请检查网络设置。" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
return;
}
- 请求中处理网络变化:在购买过程中,如果网络发生变化,需要处理正在进行的购买请求。可以监听
Reachability
的网络状态变化通知。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
- (void)handleNetworkChange:(NSNotification *)notification {
Reachability *reachability = [notification object];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
if (networkStatus == NotReachable) {
// 取消正在进行的购买请求
NSArray<SKPaymentTransaction *> *transactions = [[SKPaymentQueue defaultQueue] transactions];
for (SKPaymentTransaction *transaction in transactions) {
[[SKPaymentQueue defaultQueue] cancelTransaction:transaction];
}
// 提示用户网络中断
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"网络中断" message:@"购买过程中网络中断,请稍后重试。" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
}