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

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

我正在尝试编写一些代码来验证我的 iOS 应用程序上的订阅。我正在学习本教程:http://savvyapps.com/blog/how-setup-test-auto-renewable-subscription-ios-app/

它不在 Swift 2.0 中,所以我不得不转换一些代码,但我在处理这一行时遇到了问题:

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

当它到达该行时,它会打印此错误消息:

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

这是整个函数:

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)
            }
        })
    }
}

我以前没有做过应用内购买,所以我对此有点陌生。预先感谢您的帮助!

错误消息明确指出字典中的值之一是 JSON 不支持的 NSData 对象。

这似乎是一个代码完成问题

替换

base64EncodedDataWithOptions([])

base64EncodedStringWithOptions([])

如链接文章中所写。


两个旁注:

  • dataWithJSONObject returns NSData 无论如何,类型转换是无用的,永远不会是隐式解包可选。
  • 服务器当然不关心漂亮的打印JSON。