How to solve error: "Invalid type in JSON write (NSConcreteData)"

Nick

I'm trying to write some code to validate a subscription on my iOS App. I'm following this tutorial: http://savvyapps.com/blog/how-setup-test-auto-renewable-subscription-ios-app/

It's not in Swift 2.0, so I had to convert some of the code, but I'm having trouble with this line:

let requestData = try! NSJSONSerialization.dataWithJSONObject(receiptDictionary, options: NSJSONWritingOptions.PrettyPrinted) as NSData!

When it hits that line, it prints this error message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteData)'

Here's the whole function:

func validateReceipt() {
    print("Validating")

    if let receiptPath = NSBundle.mainBundle().appStoreReceiptURL?.path where NSFileManager.defaultManager().fileExistsAtPath(receiptPath) {
        print("Loading Validation")
        let receiptData = NSData(contentsOfURL:NSBundle.mainBundle().appStoreReceiptURL!)
        print(receiptData)
        let receiptDictionary = ["receipt-data" :
            receiptData!.base64EncodedDataWithOptions([]), "password" : "placeholder"]
        let requestData = try! NSJSONSerialization.dataWithJSONObject(receiptDictionary, options: NSJSONWritingOptions.PrettyPrinted) as NSData!

        let storeURL = NSURL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!
        let storeRequest = NSMutableURLRequest(URL: storeURL)
        storeRequest.HTTPMethod = "POST"
        storeRequest.HTTPBody = requestData

        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

        session.dataTaskWithRequest(storeRequest, completionHandler: { (data, response, connection) -> Void in

            if let jsonResponse: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as?
                NSDictionary, let expirationDate: NSDate = self.formatExpirationDateFromResponse(jsonResponse) {
                    print(expirationDate)
                    //self.updateIAPExpirationDate(expirationDate)
            }
        })
    }
}

I haven't done in-app purchases before, so I'm a bit new to this. Thanks in advance for your help!

vadian

The error message clearly states that one of the values in the dictionary is a NSData object which is not supported by JSON.

It seems that's a code completion issue

Replace

base64EncodedDataWithOptions([])

with

base64EncodedStringWithOptions([])

as written also in the linked article.


Two side notes:

  • dataWithJSONObject returns NSData anyway, the type cast is useless and would never be an implicit unwrapped optional.
  • The server certainly doesn't care about pretty printed JSON.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related