在iOS 6和7中验证购买收据

4

我正在使用以下代码验证应用内购买收据:

- (void) completeTransaction:(SKPaymentTransaction*) transaction
{   
    NSData* receipt = nil;

    // 1. Attempt <app receipt> first (iOS 7.x)

    NSBundle* mainBundle = [NSBundle mainBundle];

    if ([mainBundle respondsToSelector:@selector(appStoreReceiptURL)]) {

        NSURL* appStoreReceiptURL = [mainBundle appStoreReceiptURL]; // <- CRASH

        receipt = [NSData dataWithContentsOfURL:appStoreReceiptURL];
    }

    // 2. Fallback to <transaction receipt> (iOS < 7.0)
    if (!receipt) {    
        receipt = [transaction transactionReceipt];
    }

    // 3. Have server verify it with iTunes:    
    [self verifyReceipt:receipt forTransaction:transaction];
}

在iOS 6设备上,执行到NSURL* appStoreReceiptURL = [mainBundle appStoreReceiptURL];这一行时,控制台会报错:-[NSBundle appStoreReceiptURL]: unrecognized selector sent to instance 0x208492d0
我是否漏掉了什么?难道-respondsToSelector:不应该处理这个吗?必须直接检查操作系统版本吗?
1个回答

8

在使用appStoreReceiptURL方法时,你应该直接检查版本号。

appStoreReceiptURL

在iOS中,可以使用以下代码来检测此方法是否可用:

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
   // Load resources for iOS 6.1 or earlier
} else {
   // Load resources for iOS 7 or later
}

注意:使用 respondsToSelector: 方法进行弱链接的一般最佳实践在这里不能使用。在 iOS 7 之前,该方法(appStoreReceiptURL)被实现为私有 API,但该实现调用了 doesNotRecognizeSelector: 方法。
参考:NSBundle 类参考文档。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接