func checkForReceipt(_ restoring: Bool) {
let receiptUrl = Bundle.main.appStoreReceiptURL
let fileExists = FileManager.default.fileExists(atPath: receiptUrl!.path)
if fileExists {
getReceipt(urlString: "https://buy.itunes.apple.com/verifyReceipt") { (completion) in
if completion.value(forKey: "status") as! Int == 21007 {
print("Going to sandbox for receipt validation")
self.getReceipt(urlString: "https://sandbox.itunes.apple.com/verifyReceipt") { (completion) in
guard let expDate = self.expirationDateFromResponse(completion) else {return}
print("SANDBOX: \(expDate)")
}
} else if completion.value(forKey: "status") as! Int == 0 {
guard let expDate = self.expirationDateFromResponse(completion) else {return}
print("PRODUCTION: \(expDate)")
}
}
if restoring {
updateSub()
} else {
delegate?.setSubView()
}
} else {
print("No Receipt")
if restoring {
let alert = UIAlertView(title: "Oops!", message: "You haven't purchased a myPets subscription yet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
}
func getReceipt(urlString: String, completion: @escaping (NSDictionary) -> Void) {
var jsonResponse: NSDictionary?
let receiptURL = Bundle.main.appStoreReceiptURL
let receiptData = try? Data(contentsOf: receiptURL!)
guard let receiptToString = receiptData?.base64EncodedString(options: []) else {return}
let dict = ["receipt-data" : receiptToString, "password" : [your shared secret code]] //**
do {
let request = try JSONSerialization.data(withJSONObject: dict, options: []) as Data
var storeRequest = URLRequest(url: URL(string:urlString)!) //NSMutableURLRequest(url: storeURL)
storeRequest.httpMethod = "POST"
storeRequest.httpBody = request
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: storeRequest, completionHandler: { (data, response, error) in
if let error = error {
print(error.localizedDescription)
return
}
do {
jsonResponse = try (JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary)!
completion(jsonResponse!)
} catch {
//handle NSJSONSerialization errors
print(error.localizedDescription)
}
})
task.resume()
} catch {
print(error.localizedDescription)
//handle NSJSONSerialization errors
}
func expirationDateFromResponse(_ jsonResponse: NSDictionary) -> Date? {
if let receiptInfo: NSArray = jsonResponse["latest_receipt_info"] as? NSArray {
guard let lastReceipt = receiptInfo.lastObject as? NSDictionary else {return nil}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
guard let expirationDate: Date = formatter.date(from: (lastReceipt["expires_date"] as! String)) else {return nil}
currentSub = lastReceipt["product_id"] as! String
currentSubExpiry = expirationDate
saveSub()
return expirationDate
} else {
return nil
}
}