rigdonmr rigdonmr - 1 year ago 73
Swift Question

iOS: How to detect if a user is subscribed to an auto-renewable subscription

Hopefully the title is self-explanatory. I'm trying to do something like this:

checkIfUserIsSubscribedToProduct(productID, transactionID: "some-unique-transaction-string", completion: { error, status in
if error == nil {
if status == .Subscribed {
// do something fun

does anything like the hypothetical code I've provided exist? I feel like I'm taking crazy pills


In similar questions I keep seeing a generic answer of "oh you gotta validate the receipt" but no explanation on how, or even what a receipt is. Could someone provide me with how to "validate the receipt"? I tried this tutorial but didn't seem to work.

Edit - For Bounty

Please address the following situation: A user subscribes to my auto-renewable subscription and gets more digital content because of it - cool, implemented. But how do I check whether that subscription is still valid (i.e. they did not cancel their subscription) each time they open the app? What is the simplest solution to check this? Is there something like the hypothetical code I provided in my question? Please walk me through this and provide any further details on the subject that may be helpful.

Answer Source

I know everyone was very concerned about me and how I was doing on this - fear not, solved my problem. Main problem was that I tried the garbage and outdated code in this link, but it wasn't working so I gave up on it. Then I came back to it and implemented it with Alamofire and it works great. Here's the code solution:

let receiptURL = NSBundle.mainBundle().appStoreReceiptURL
let receipt = NSData(contentsOfURL: receiptURL!)
let requestContents = [
    "receipt-data": receipt!.base64EncodedStringWithOptions([]),
    "password": "5e6e3b769b504bc9bb175786fe7a6114"
let requestData = try! NSJSONSerialization.dataWithJSONObject(requestContents, options: [])
let storeURL = NSURL(string: "https://buy.itunes.apple.com/verifyReceipt")
let request = NSMutableURLRequest(URL: storeURL!)
request.HTTPMethod = "POST"
request.HTTPBody = requestData
let (params, _) = Alamofire.ParameterEncoding.URL.encode(request, parameters: nil)
Alamofire.request(params).responseJSON { response in
    let data = try! NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions.AllowFragments)
    let json = JSON(data) // SwiftyJSON
    let expiresTime = json["receipt"]["in_app"][0]["expires_date_ms"].doubleValue / 1000
    let currentTime = NSDate().timeIntervalSince1970
    let expired = currentTime < expiresTime