Created
February 16, 2017 18:50
-
-
Save jonathanpeppers/e0789adf6046a1c875f41a750694759b to your computer and use it in GitHub Desktop.
ApplePurchaseService - GetPrices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ApplePurchaseService : PurchaseService | |
{ | |
public async override Task<Purchase[]> GetPrices(params string[] ids) | |
{ | |
using (var del = new RequestDelegate()) | |
using (var request = new SKProductsRequest(new NSSet(ids)) | |
{ | |
Delegate = del, | |
}) | |
{ | |
request.Start(); | |
return await del.Source.Task; | |
} | |
} | |
private class RequestDelegate : SKProductsRequestDelegate | |
{ | |
private readonly NSNumberFormatter _formatter = new NSNumberFormatter | |
{ | |
FormatterBehavior = NSNumberFormatterBehavior.Version_10_4, | |
NumberStyle = NSNumberFormatterStyle.Currency, | |
}; | |
public readonly TaskCompletionSource<Purchase[]> Source = new TaskCompletionSource<Purchase[]>(); | |
public override void ReceivedResponse(SKProductsRequest request, SKProductsResponse response) | |
{ | |
if (response.Products == null || response.Products.Length == 0) | |
{ | |
Source.TrySetException(new Exception("No products were found!")); | |
return; | |
} | |
var list = new List<Purchase>(); | |
foreach (var product in response.Products) | |
{ | |
list.Add(new Purchase | |
{ | |
Id = product.ProductIdentifier, | |
Price = _formatter.StringFromNumber(product.Price), | |
NativeObject = product, | |
}); | |
} | |
Source.TrySetResult(list.ToArray()); | |
} | |
public override void RequestFailed(SKRequest request, NSError error) | |
{ | |
Source.TrySetException(new Exception(error?.LocalizedDescription ?? "Unknown Error")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment