我想将SKPayment交易存储在用户默认值或设备上,我还想将交易数据存储在我的服务器上以后(尚未完成),以便用户可以恢复订阅如果需要/必要/可能。
我遇到的问题是我尝试保存到用户默认值,但它一直告诉我:
* - [NSUserDefaults setObject:forKey:]:尝试插入非属性值'{ transaction =“”; ''class'__NSCFDictionary'。
我使用的代码是:
// Save
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:transaction forKey:@"transaction"];
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"TransactionReceipt"];
[[NSUserDefaults standardUserDefaults] synchronize];
// Read
NSMutableDictionary *savedDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyTransactionReceipt"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"Saved stored transaction = %@", savedDict);
我也尝试保存Transaction对象本身,而不是将其存储在字典中,但这总是会给出错误,它会抱怨
“尝试插入非插入属性值...”
我也尝试过使用NSKeyedArchiver,但我不知道如何编写它来处理SKPaymentTransaction的读写。
对此的任何帮助都将非常感激。
谢谢。
答案 0 :(得分:6)
我通过将事务数据存储在文档目录中的plist中来解决问题。
这对我的要求来说更容易,也更可靠。
基本代码适用于那些希望这样做的人。
// WRITING
// Save to documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *receiptStorageFile = [documentsDirectory stringByAppendingPathComponent:@"receipts.plist"];
NSLog(@"Reciept Storage File = %@", receiptStorageFile);
NSMutableArray *receiptStorage = [[NSMutableArray alloc] initWithContentsOfFile:receiptStorageFile];
if(!receiptStorage) {
receiptStorage = [[NSMutableArray alloc] init];
}
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:transaction.transactionIdentifier forKey:@"transactionIdentifier"];
[dict setObject:transaction.transactionDate forKey:@"transactionDate"];
[dict setObject:transaction.transactionReceipt forKey:@"transactionReceipt"];
// Write
[receiptStorage addObject:dict];
[receiptStorage writeToFile:receiptStorageFile atomically:YES];
[receiptStorage release];
// READING
// Get app documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"DocumentsDirectory = %@", documentsDirectory);
// Load from documents directory
NSArray *receipts = [[[NSArray alloc] initWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:@"receipts.plist"]] autorelease];
// Found a receipt on disk
if ([receipts count]>0) {
// Do something, read the dictionary, etc.
} // end if