【发布时间】:2012-07-24 14:14:14
【问题描述】:
我正在尝试将 Beeblex 的新应用内购买验证添加到我的应用中,但是我正在努力从块内传递返回值。
这是我现在拥有的代码,如您所见,我设置了一个 BOOL 值,然后在验证块中设置了 BOOL 并在最后返回它。但是最后的 return 是在块完成之前调用的,所以我需要从块内返回 BOOL?
- (BOOL)verifyTransaction:(SKPaymentTransaction *)transaction
{
if (![BBXIAPTransaction canValidateTransactions]) {
return YES; // There is no connectivity to reach the server
}
BOOL __block toReturn = YES;
BBXIAPTransaction *bbxTransaction = [[BBXIAPTransaction alloc] initWithTransaction:transaction];
bbxTransaction.useSandbox = YES;
[bbxTransaction validateWithCompletionBlock:^(NSError *error) {
if (bbxTransaction.transactionVerified) {
if (bbxTransaction.transactionIsDuplicate) {
// The transaction is valid, but duplicate - it has already been sent to Beeblex in the past.
NSLog(@"Transaction is a duplicate!");
[FlurryAnalytics logEvent:@"Transaction duplicate!"];
toReturn = NO;
} else {
// The transaction has been successfully validated and is unique
NSLog(@"Transaction valid data:%@",bbxTransaction.validatedTransactionData);
[FlurryAnalytics logEvent:@"Transaction verified"];
toReturn = YES;
}
} else {
// Check whether this is a validation error, or if something went wrong with Beeblex
if (bbxTransaction.hasConfigurationError || bbxTransaction.hasServerError || bbxTransaction.hasClientError) {
// The error was not caused by a problem with the data, but is most likely due to some transient networking issues
NSLog(@"Transaction error caused by network, not data");
[FlurryAnalytics logEvent:@"Transaction network error"];
toReturn = YES;
} else {
// The transaction supplied to the validation service was not valid according to Apple
NSLog(@"Transaction not valid according to Apple");
[FlurryAnalytics logEvent:@"Transaction invalid!!"];
toReturn = NO;
}
}
}];
NSLog(@"toReturn: %@",toReturn ? @"Yes" : @"No");
return toReturn;
}
如果我只是将return = NO; 放在块内,我会收到不兼容块指针类型的编译器警告,并且控制可能会到达非空块的末尾。
【问题讨论】:
-
这是一个奇怪的事情,因为块与方法不同步,因此无论你想为块内的
toReturn变量设置什么值,方法都不会处理它,当线程池运行return toReturn;行时,它会发回当前的toReturn值。 -
您正在尝试将异步 API 转换为同步 API,这是错误的做法。而不是返回
BOOL,您的代码应该采用完成块或它自己的委托,在事务完成时回调调用者。使 API 同步会降低您的应用程序的响应速度。 -
是的,我想这是有道理的,我正在尝试将异步变为同步,这并不好。在这种情况下,我可以在块内使用 [self successMethod] 和 [self failMethod] 来调用单独的方法。谢谢
标签: objective-c ios xcode cocoa-touch objective-c-blocks