Search code examples
swiftin-app-purchase

date of app purchase date in Swift, start or end date


I use the feature of purchase for weekly and monthly application. Each time the user opens the app, check his or her purchase, if he/she have purchased, how can get both the subscription start and end date


Solution

  • Fiko! You should validate your App Store receipt and get subscription info from there.

    Here is basic example of validating receipt:

    func validateReceipt(){
    
            #if DEBUG
                       let urlString = "https://sandbox.itunes.apple.com/verifyReceipt"
                   #else 
                       let urlString = "https://buy.itunes.apple.com/verifyReceipt"
                   #endif
    
            guard let receiptURL = Bundle.main.appStoreReceiptURL, let receiptString = try? Data(contentsOf: receiptURL).base64EncodedString() , let url = URL(string: urlString) else {
                    return
            }
    
            let requestData : [String : Any] = ["receipt-data" : receiptString, 
                                                "password" : "YOUR_SHARED_SECRET", 
                                                "exclude-old-transactions" : false]
            let httpBody = try? JSONSerialization.data(withJSONObject: requestData, options: [])
    
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
            request.httpBody = httpBody
            URLSession.shared.dataTask(with: request)  { (data, response, error) in
                // convert data to Dictionary and view purchases
            }.resume()        
        }
    

    After you validated a receipt, you should convert data to Dictionary and get expiration date in latest_receipt_info

    You can use our Apphud SDK to track subscriptions info, including start and end date.

    Also you can use SwiftyStoreKit library, you can get subscription info there as well.

    If you want to do this manually, then here is good article in our blog: https://blog.apphud.com/swift-tutorial-subscriptions/