如何在Swift中显示第一个视图之前检查订阅状态

时间:2018-07-24 02:26:42

标签: swift xcode in-app-purchase subscription auto-renewable

我在Swift中实现了订阅(自动续订购买)。如果用户已经下标,我想在第一个视图中显示一个按钮,如果没有,请隐藏该按钮。

我进行了预订代码,但是在出现第一个视图之后它可以工作。因此,如果在订阅有效时尝试隐藏该按钮,则该按钮将在按钮已出现后被隐藏。

现在它的工作方式如下:
1.启动应用程序
2.执行功能“ checkReceipt()”,该功能检查预订在AppDelegate中是否有效(但现在总是返回“ false”,即使它应该是有效的)
3.第一个视图出现了
4.完成checkReceipt()并返回true(有效)

我想在第一个视图出现之前检查订阅是否正确有效。我该如何解决这个问题?

(我使用来自here的订阅代码)

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate, SKPaymentManagerDelegate {

    var window: UIWindow?
    var isValid: Bool!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // check receipt
        SKPaymentManager.shared().delegate = self
        SKPaymentQueue.default().add(SKPaymentManager.shared())

        isValid = SKPaymentManager.checkReceipt()

        return true
    }
//...

SKProductManager

import Foundation
import StoreKit

fileprivate var productManagers : Set<SKProductManager> = Set()

class SKProductManager: NSObject, SKProductsRequestDelegate {
    static var subscriptionProduct : SKProduct? = nil

    fileprivate var completion : (([SKProduct]?,NSError?) -> Void)?

    static func getProducts(withProductIdentifiers productIdentifiers : [String],completion:(([SKProduct]?,NSError?) -> Void)?){
        let productManager = SKProductManager()
        productManager.completion = completion
        let request = SKProductsRequest(productIdentifiers: Set(productIdentifiers))
        request.delegate = productManager
        request.start()

        productManagers.insert(productManager)
    }

    static func getSubscriptionProduct(completion:(() -> Void)? = nil) {

        guard SKProductManager.subscriptionProduct == nil else {
            if let completion = completion {
                completion()
            }
            return
        }

        let productIdentifier = "secret" 

        SKProductManager.getProducts(withProductIdentifiers: [productIdentifier], completion: { (_products, error) -> Void in
            if let product = _products?.first {
                SKProductManager.subscriptionProduct = product
            }
            if let completion = completion {
                completion()
            }
        })

    }

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        var error : NSError? = nil
        if response.products.count == 0 {
            error = NSError(domain: "ProductsRequestErrorDomain", code: 0, userInfo: [NSLocalizedDescriptionKey:"couldn't get product"])
        }
        completion?(response.products, error)
    }

    func request(_ request: SKRequest, didFailWithError error: Error) {
        let error = NSError(domain: "ProductsRequestErrorDomain", code: 0, userInfo: [NSLocalizedDescriptionKey:"couldn't get product "])
        completion?(nil,error)
        productManagers.remove(self)
    }
    func requestDidFinish(_ request: SKRequest) {
        productManagers.remove(self)
    }
}

SKPaymentManager

///...
public static func checkReceipt() -> Bool {

var date = NSDate()
var check = false

do {
    let reqeust = try getReceiptRequest()
    let session = URLSession.shared
    let task = session.dataTask(with: reqeust, completionHandler: {(data, response, error) -> Void in
        guard let jsonData = data else { return }

        do {
            let json = try JSONSerialization.jsonObject(with: jsonData, options: .init(rawValue: 0)) as AnyObject
            receiptStatus = ReceiptStatusError.statusForErrorCode(json.object(forKey: "status"))
            guard let latest_receipt_info = (json as AnyObject).object(forKey: "latest_receipt_info") else { return }
            guard let receipts = latest_receipt_info as? [[String: AnyObject]] else { return }
            updateStatus(receipts: receipts)
            var latest = receipts.last

            date = NSDate()
            if let result = latest!["expires_date"] as? String {
                let expireDate = result
                check = checkDifference(now: date, expireDate: expireDate)
                let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
                appDelegate.isValid = check
            }

        } catch _ {

        }
    })
    task.resume()
} catch let error {
    print("SKPaymentManager : Failure to process payment from Apple store: \(error)")
    checkReceiptInLocal()
}

return check

}

/// check subscription is valid or not
fileprivate static func checkDifference(now: NSDate, expireDate: String) -> Bool{

    // convert string to Date
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
    let expire = dateFormatter.date(from: expireDate)

    let dateComponentsFormatter = DateComponentsFormatter()
    dateComponentsFormatter.allowedUnits = [.year,.month,.weekOfMonth,.day,.hour,.minute,.second]
    dateComponentsFormatter.maximumUnitCount = 1
    dateComponentsFormatter.unitsStyle = .full

    dateComponentsFormatter.string(from: now as Date, to: Date(timeIntervalSinceNow: 4000000))  // "1 month"
    dateComponentsFormatter.string(from: expire!, to: Date(timeIntervalSinceNow: 4000000))  // "1 month"

    let seconds = expire?.seconds(from: now as Date)  

    if seconds! > 0 {
        return true
    }else{
        return false
    }

}
///...

1 个答案:

答案 0 :(得分:0)

问题在于checkReceipt()不是异步调用,因此在设置isValid时没有任何反应。您可以通过在AppDelegate中以编程方式设置应用程序的初始视图,然后修改checkReceipt()函数以接受类型为(Bool)->()的闭包,来完成所需的操作。如果使用情节提要,则需要首先通过取消选中“属性”检查器中“视图控制器”标题下的“是初始视图控制器”来删除初始视图控制器。

在SKPaymentManager中,将checkReceipt() -> Bool {更改为checkReceipt(handler:(Bool)->()) {,然后:

check = checkDifference(now: date, expireDate: expireDate)
//delete the two lines that follow and replace them with the asynchronous call:
handler(check)

重要提示:还请记住在每个handler(false)块和catch语句的guard块中添加else {,以便即使出现错误也可以加载应用程序。

接下来,在application(:,didFinishLaunchingWithOptions:):

//step 1: make variables for window and storyboard. Storyboard name parameter is the storyboard's filename.
var window = UIWindow()
let storyboard = UIStoryboard(name: "Main", bundle: nil) 
//step 2: instantiate your initial view controller. 
let initialViewController = storyboard.instantiateViewController(withIdentifier:"identifier") as InitialViewController()!
//step 3: make the asynchronous call
checkReceipts(handler: { valid in
    self.isValid = valid
    initialViewController.subscribeButton.isHidden = valid == false //hide if valid
    //step 4: set the window's root view controller 
    window?.rootViewController = initialViewController
    window?.makeKeyAndVisible()
}) 

享受:]