Search code examples
iosswiftstorekit

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

Edit

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.


Solution

  • 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 Apple's example code from the documentation, 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:

    Swift 3:

    let receiptURL = Bundle.main.appStoreReceiptURL
    let receipt = NSData(contentsOf: receiptURL!)
    let requestContents: [String: Any] = [
        "receipt-data": receipt!.base64EncodedString(options: []),
        "password": "your iTunes Connect shared secret"
    ]
    
    let appleServer = receiptURL?.lastPathComponent == "sandboxReceipt" ? "sandbox" : "buy"
    
    let stringURL = "https://\(appleServer).itunes.apple.com/verifyReceipt"
    
    print("Loading user receipt: \(stringURL)...")
    
    Alamofire.request(stringURL, method: .post, parameters: requestContents, encoding: JSONEncoding.default)
        .responseJSON { response in
            if let value = response.result.value as? NSDictionary {
                print(value)
            } else {
                print("Receiving receipt from App Store failed: \(response.result)")
            }
    }