我尝试编写一些代码来验证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!
当它到达该行时,它会输出以下错误消息:
由于未捕获的异常而终止应用 ' NSInvalidArgumentException',原因:' JSON写入中的无效类型 (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)
}
})
}
}
之前我没有完成应用内购买,所以我对此有点新鲜。在此先感谢您的帮助!
答案 0 :(得分:3)
错误消息明确指出字典中的一个值是JSON不支持的NSData
对象。
这似乎是代码完成问题
替换
base64Encoded 数据强> WithOptions([])
与
base64Encoded的字符串强> WithOptions([])
也在链接文章中写道。
两个旁注:
dataWithJSONObject
返回NSData
,类型转换是无用的,永远不会是隐式解包的可选项。