我尝试如何在我的项目中实现可消耗的应用内购买。
教程:
我已经阅读了这些教程,但我不知道 DependencyService、Debug 和 Device 是什么。我收到以下错误消息:
错误 CS0103:当前上下文中不存在名称“DependencyService”(CS0103) 错误 CS0103:当前上下文中不存在名称“设备”(CS0103) 错误 CS0103:当前上下文中不存在名称“调试”上下文 (CS0103)
另外,我不明白这行代码是什么意思。为什么我们要检查 Device.RuntimePlatform == Device.iOS ?如果是真的我该怎么办,如果是假的我该怎么办?
if(Device.RuntimePlatform == Device.iOS)
return;
这就是我在我的项目中实现代码的方式:
string payload = "apppayload";
public async Task<bool> PurchaseItem(string productId, string payload)
{
if (!CrossInAppBilling.IsSupported)
return false;
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync(ItemType.InAppPurchase);
if (!connected)
{
//we are offline or can't connect, don't try to purchase
return false;
}
var verify = DependencyService.Get<IInAppBillingVerifyPurchase>();
//check purchases
var purchase = await billing.PurchaseAsync(productId, ItemType.InAppPurchase, payload, verify);
//possibility that a null came through.
if (purchase == null)
{
//did not purchase
}
else if (purchase.State == PurchaseState.Purchased)
{
//purchased, we can now consume the item or do it later
//If we are on iOS we are done, else try to consume the purchase
//Device.RuntimePlatform comes from Xamarin.Forms, you can also use a conditional flag or the DeviceInfo plugin
if (Device.RuntimePlatform == Device.iOS)
return false;
var consumedItem = await CrossInAppBilling.Current.ConsumePurchaseAsync(purchase.ProductId, purchase.PurchaseToken);
if (consumedItem != null)
{
//Consumed!!
}
}
}
catch (InAppBillingPurchaseException purchaseEx)
{
//Billing Exception handle this based on the type
Debug.WriteLine("Error: " + purchaseEx);
}
catch (Exception ex)
{
//Something else has gone wrong, log it
Debug.WriteLine("Issue connecting: " + ex);
}
finally
{
await billing.DisconnectAsync();
}
return false;
}
嗯...“DependencyService”和“Device”是 Xamarin.Forms 的子类,所以如果你还没有这样做,请添加:
using Xamarin.Forms;
在你的代码之上
如果 DependencyService/Debug 仍然不存在,我认为您在错误的项目中,您需要在“便携式”项目中使用它,而不是在与操作系统相关的项目中。尝试研究跨平台 xamarin 项目的工作原理:)
军团-
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句