确保 iOS 应用程序与后端之间的通信成功

Ensure that communication between iOS application and back-end succeeded

简单问题:如何确保iOS应用程序与后端通信成功?


详情:对于我们手机应用中的大部分API调用,如果应用与服务端通信失败,可以"OK" (出于网络原因或其他原因),我们可以使用重试按钮向用户显示一条消息,例如重新加载他的新闻或帖子提要。

然而,在某些情况下,我们想要真正确信应用程序和后端之间的通信永远不会失败,并且此通信的数据可能是 "lost"。

为此,我们以应用内购买 (IAP) 为例:

struct InAppPurchase{
   // The id of the purchase
   let transactionId: String 
   // The id of the user who purchased
   let userId: String 
   // The IAP product involved in the purchase (10 or 30 in-app coins for example)
   let productId: String 
}

我在想这个方法:

var pendingPurchases = [InAppPurchase]()

您如何看待这种做法?您如何管理这种您不想成为的数据?"lost"?

您要做的是等待 "finish the transaction",直到您从服务器收到 200 响应。如果您没有完成交易,Apple 会将其保存在付款队列中,并在每次应用程序启动时继续将其发送给您。这将使您有机会在需要时处理对服务器的任何重试。

Finishing a transaction tells StoreKit that you’ve completed everything needed for the purchase. Unfinished transactions remain in the queue until they’re finished, and the transaction queue observer is called every time your app is launched so your app can finish the transactions. Your app needs to finish every transaction, regardless of whether the transaction succeeded or failed.

Complete all of the following actions before you finish the transaction:

  • Persist the purchase.
  • Download associated content.
  • Update your app’s UI to let the user access the product.

要完成交易,请调用付款队列上的 finishTransaction: 方法。

SKPaymentTransaction *transaction = <# The current payment #>;
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];

您可以在下面的 Apple 文档中阅读有关完成交易的更多信息: https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/DeliverProduct.html