我想在Swift中启动应用程序之前检查收据。最初,我在didFinishLaunchingWithOptions
,AppDelegate
中编写了代码。但是它在第一个ViewController
出现后就完成了检查。
我要更改举动取决于应用程序内购买(订阅)是否有效。
我该如何实施?
AppDelegate
import StoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, SKPaymentManagerDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
SKProductManager.getSubscriptionProduct()
SKPaymentManager.shared().delegate = self
SKPaymentQueue.default().add(SKPaymentManager.shared())
SKPaymentManager.checkReceipt(handler: { valid in
receiptValidation()
isSubscriptionValid = valid
hideBlock(isValid: isSubscriptionValid) //if subscription is valid, hide all "block" objects in App
self.window?.makeKeyAndVisible()
})
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(handler:@escaping (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 _ {
handler(false)
}
})
task.resume()
} catch let error {
print("SKPaymentManager : Failure to process payment from Apple store: \(error)")
checkReceiptInLocal()
handler(false)
}
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
}
}
///...