- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
你好,我有工作应用程序,当用户点击购买限制 View Controller (第一次点击)时,用户购买了一切好东西,但是当用户返回主 Controller 并再次购买限制 View Controller 时,用户点击购买 IAP 进行双重交易和用户当点击购买 IAP 进行三重交易时,也再次进入主 Controller 并再次购买限制 View Controller ..我如何解决这个问题我的代码如下。
支付管理器
import UIKit
import StoreKit
protocol PurchaseManagerDelegate
{
func refreshList()
func restoreCompleted()
func transactionIsActive()
}
class PurchaseManager: NSObject
{
var productsArray = [SKProduct]()
var purchaseItemID = ""
var getprice:NSDecimalNumber = 0.00
var delegate: PurchaseManagerDelegate?
var transactionProgress = false
var productsLoadedNotification = "productsLoadedNotification"
var appusername:String? = prefs.valueForKey("email") as! String!
// MARK: - Load product methods
func loadPaymentInfo()
{
requestProductInfo()
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
}
func requestProductInfo()
{
let productIDs = getProductIDs()
if SKPaymentQueue.canMakePayments()
{
let productRequest = SKProductsRequest(productIdentifiers: productIDs)
productRequest.delegate = self
productRequest.start()
}
else
{
print("Cannot perform In App Purchases.")
}
}
func getProductIDs() -> Set<String>
{
var result = Set<String>()
if let path = NSBundle.mainBundle().pathForResource("PurchaseID", ofType: "plist")
{
if let items = NSArray(contentsOfFile: path)
{
for purchaseGroups in items
{
if let array = purchaseGroups as? [String]
{
for purchaseID in array
{
result.insert(purchaseID)
}
}
}
}
}
return result
}
// MARK: - Purchase methods
func buyProduct(productID: String)
{
if transactionProgress
{
self.delegate?.transactionIsActive()
return
}
for product in productsArray
{
let payment:SKMutablePayment = SKMutablePayment(product: product)
if (productID == product.productIdentifier)
{
purchaseItemID = product.productIdentifier
getprice = product.price
payment.applicationUsername = self.appusername!;
SKPaymentQueue.defaultQueue().addPayment(payment)
self.transactionProgress = true
}
}
}
func restorePurchases()
{
if transactionProgress
{
self.delegate?.transactionIsActive()
return
}
transactionProgress = true
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}
// MARK: - Functional methods
func getProductTitle(productID: String) -> String?
{
for product in productsArray
{
if (productID == product.productIdentifier)
{
return product.localizedTitle
}
}
return nil
}
func getProductPrice(productID: String) -> String?
{
for product in productsArray
{
if (productID == product.productIdentifier)
{
let numberFormatter = NSNumberFormatter()
numberFormatter.formatterBehavior = .Behavior10_4
numberFormatter.numberStyle = .CurrencyStyle
numberFormatter.locale = product.priceLocale
return numberFormatter.stringFromNumber(product.price)!
}
}
return nil
}
func productsAreLoaded() -> Bool
{
if (productsArray.count > 0)
{
return true
}
else
{
return false
}
}
func isProductBought(productID: String) -> Bool
{
if(productID == "com.blaSupport" || productID == "com.bla.Show"){
return false
}else{
return false
}
}
}
// MARK: - Product request methods
extension PurchaseManager: SKProductsRequestDelegate
{
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse)
{
if response.products.count != 0
{
productsArray = response.products
}
if response.invalidProductIdentifiers.count != 0
{
print(response.invalidProductIdentifiers.description)
}
NSNotificationCenter.defaultCenter().postNotificationName(productsLoadedNotification, object: nil)
}
}
// MARK: - Transaction delegate methods
extension PurchaseManager: SKPaymentTransactionObserver
{
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction])
{
for transaction in transactions
{
switch transaction.transactionState
{
case .Purchasing:
print("Transaction in Progress")
case .Purchased:
print("Transaction completed successfully.")
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
// SUCCESS GIVE LIMITS
self.transactionProgress = false
// Give limits
BuyLimitsViewController.sharedInstance.giveLimits(self.purchaseItemID)
self.setPurchasedProduct(self.purchaseItemID)
self.delegate?.refreshList()
// Send Values
let addIAPUrl = "http://bla.com/)&price=\(getprice)"
self.sendIAP(addIAPUrl, completionHandler: { (success, message) -> Void in
if(success == 1){
dispatch_async(dispatch_get_main_queue()){
// ADDED
}
}else{
// DONT ADDED
}
})
case .Failed:
print("Transaction Failed");
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
transactionProgress = false
self.delegate?.refreshList()
case .Restored:
print("Restore completed successfully.")
let identifier = transaction.originalTransaction!.payment.productIdentifier
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
transactionProgress = false
self.setPurchasedProduct(identifier)
case .Deferred:
print("Transaction defered.")
print(transaction.transactionState.rawValue)
transactionProgress = false
self.delegate?.refreshList()
}
}
}
func sendIAP(url : String, completionHandler : ((success : Int, message : String) -> Void)) {
guard let url = NSURL(string: url as String) else {
completionHandler(success: 0, message: "Couldn't get URL")
return
}
let urlRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
guard let responseData = data else {
completionHandler(success: 0, message: "Data was nil")
return
}
guard error == nil else {
print(error)
completionHandler(success: 0, message: "Error wasn't nil")
return
}
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
completionHandler(success: 0, message: "Error with NSJSONSerialization")
return
}
let numberFromString = Int((post["success"] as? String)!)
completionHandler(success: (numberFromString)!, message: (post["message"] as? String)!)
})
task.resume()
}
func setPurchasedProduct(productID: NSString)
{
NSUserDefaults.standardUserDefaults().setBool(true, forKey: productID as String)
NSUserDefaults.standardUserDefaults().synchronize()
}
func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
print("Restore Completed")
self.delegate?.restoreCompleted()
}
}
这是我的 buyView Controller
import UIKit
import StoreKit
class BuyLimitsViewController: UIViewController, UITextFieldDelegate, PurchaseManagerDelegate, UITableViewDataSource, UITableViewDelegate{
static let sharedInstance = BuyLimitsViewController()
@IBOutlet weak var tableView: UITableView!
var items = []
var purchaseManager = PurchaseManager()
override func viewDidLoad() {
super.viewDidLoad()
purchaseManager.delegate = self
purchaseManager.loadPaymentInfo()
if let path = NSBundle.mainBundle().pathForResource("PurchaseID", ofType: "plist")
{
if let fileItems = NSArray(contentsOfFile: path)
{
items = fileItems
}
}
let mainQueue = NSOperationQueue.mainQueue()
NSNotificationCenter.defaultCenter().addObserverForName(purchaseManager.productsLoadedNotification, object: nil, queue: mainQueue) { _ in
self.tableView.reloadData()
}
}
// MARK: - TableView delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return items.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
var numberOfItems = 0
if let purchaseItems = items[section] as? [String]
{
numberOfItems = purchaseItems.count
}
return numberOfItems
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("StoreTableViewCell") as! StoreTableViewCell
if let purchaseItems = items[indexPath.section] as? [String]
{
let productID = purchaseItems[indexPath.row]
if purchaseManager.productsAreLoaded()
{
cell.accessoryView = nil
cell.titleLabel.text = purchaseManager.getProductTitle(productID)
cell.priceLabel.text = purchaseManager.getProductPrice(purchaseItems[indexPath.row])
}
else
{
cell.titleLabel.text = ""
cell.priceLabel.text = ""
if (indexPath.section == 0) && (indexPath.row == 0)
{
cell.titleLabel.text = "Loading..."
cell.accessoryView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
(cell.accessoryView as! UIActivityIndicatorView).startAnimating()
}
}
}
return cell
}
func giveLimits(purhased : NSString) {
let postEndpointLost:NSString = "http://bla.com/"
user.sharedInstance.apiRequest(postEndpointLost as String, completionHandler: { (success, message) -> Void in
if(success == 1){
dispatch_async(dispatch_get_main_queue()){
}
}else{
dispatch_async(dispatch_get_main_queue()){
}
}
})
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if let purchaseItems = items[indexPath.section] as? [String]
{
let productID = purchaseItems[indexPath.row]
if !purchaseManager.isProductBought(productID)
{
purchaseManager.buyProduct(purchaseItems[indexPath.row])
}
}
}
@IBAction func restoreButtonSelector(sender: AnyObject) {
purchaseManager.restorePurchases()
}
// MARK: - Purchase Manager delegate
func refreshList()
{
self.tableView.reloadData()
}
func transactionIsActive()
{
let alert = UIAlertController(title: "", message: "Transaction is already in progress. Please wait to finish.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { alertAction in
self.tableView.reloadData()
alert.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
func restoreCompleted()
{
let alert = UIAlertController(title: "", message: "Restore completed.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { alertAction in
self.tableView.reloadData()
alert.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
每次加载buyviewcontroller +1 count这个输出例子的输出例子
Transaction in Progress
Transaction in Progress
Transaction in Progress
Transaction in Progress
我想当用户点击购买限制 View Controller 时可能需要清除一些东西我需要你的帮助谢谢!
最佳答案
您没有执行 removeTransactionObserver
。所以每次在 viewDidLoad()
中它都会在默认的 paymentQueue 上添加事务观察器
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
为了解决这个问题,请在 viewWillDisappear
中执行 removeTransactionObserver
。在 StoreViewController
中写入:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
purchaseManager.removeTransactionObserver()
}
在PurchaseManager
中添加一个函数:
func removeTransactionObserver()
{
SKPaymentQueue.defaultQueue().removeTransactionObserver(self)
}
关于ios - 返回并再次打开 View Controller 时的Swift IAP多个事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35733249/
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
在编码时,我问了自己这个问题: 这样更快吗: if(false) return true; else return false; 比这个? if(false) return true; return
如何在逻辑条件下进行“返回”? 在这样的情况下这会很有用 checkConfig() || return false; var iNeedThis=doSomething() || return fa
这是我的正则表达式 demo 如问题所述: 如果第一个数字是 1 则返回 1 但如果是 145 则返回 145 但如果是 133 则返回 133 样本数据a: K'8134567 K'81345678
在代码高尔夫问答部分查看谜题和答案时,我遇到了 this solution返回 1 的最长和最晦涩的方法 引用答案, int foo(void) { return! 0; } int bar(
我想在下面返回 JSON。 { "name": "jackie" } postman 给我错误。说明 Unexpected 'n' 这里是 Spring Boot 的新手。 1日龄。有没有正确的方法来
只要“is”返回 True,“==”不应该返回 True 吗? In [101]: np.NAN is np.nan is np.NaN Out[101]: True In [102]: np.NAN
我需要获取所有在 6 号或 7 号房间或根本不在任何房间的学生的详细信息。如果他们在其他房间,简单地说,我不希望有那个记录。 我的架构是: students(roll_no, name,class,.
我有一个表单,我将它发送到 php 以通过 ajax 插入到 mysql 数据库中。一切顺利,php 返回 "true" 值,但在 ajax 中它显示 false 消息。 在这里你可以查看php代码:
我在 Kotlin 中遇到了一个非常奇怪的无法解释的值比较问题,以下代码打印 假 data class Foo ( val a: Byte ) fun main() { val NUM
请注意,这并非特定于 Protractor。问题在于 Angular 2 的内置 Testability service Protractor 碰巧使用。 Protractor 调用 Testabil
在调试窗口中,以下表达式均返回 1。 Application.WorksheetFunction.CountA(Cells(4 + (i - 1) * rows_per_record, 28) & "
我在本地使用 jsonplaceholder ( http://jsonplaceholder.typicode.com/)。我正在通过 extjs rest 代理测试我的 GET 和 POST 调用
这是 Postman 为成功调用我的页面而提供的(修改后的)代码段。 var client = new RestClient("http://sub.example.com/wp-json/wp/v2
这个问题在这里已经有了答案: What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must
我想我对 C 命令行参数有点生疏。我查看了我的一些旧代码,但无论这个版本是什么,都会出现段错误。 运行方式是 ./foo -n num(其中 num 是用户在命令行中输入的数字) 但不知何故它不起作用
我已经编写了一个类来处理命名管道连接,如果我创建了一个实例,关闭它,然后尝试创建另一个实例,调用 CreateFile() 返回 INVALID_HANDLE_VALUE,并且 GetLastErro
即使 is_writable() 返回 true,我也无法写入文件。当然,该文件存在并且显然是可读的。这是代码: $file = "data"; echo file_get_contents($fil
下面代码中的变量 $response 为 NULL,尽管它应该是 SOAP 请求的值。 (潮汐列表)。当我调用 $client->__getLastResponse() 时,我从 SOAP 服务获得了
我一直在网上的不同论坛上搜索答案,但似乎没有与我的情况相符的... 我正在使用 Windows 7,VS2010。 我有一个使用定时器来调用任务栏刷新功能的应用程序。在该任务栏函数中包含对 LoadI
我是一名优秀的程序员,十分优秀!