В моем приложении я поддерживаю только евро и доллары США. Поэтому, когда пользователь пытается отправить платеж с помощью Siri, например, в фунты стерлингов, я прошу его выбрать между евро и долларами США.
После этого на экране я вижу:
- 100 $
- 100 евро
Если я выберу 100 долларов в intent.currencyAmount!.currencyCode
, у меня всегда будут фунты стерлингов (но пользователь выбрал доллары). Это очень странно.
Вот мой код:
func resolveCurrencyAmount(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INCurrencyAmountResolutionResult) -> Void) {
if let currencyAmount = intent.currencyAmount { // need to check if we have proper value
if let amount = currencyAmount.amount {
if amount.doubleValue == 0 { // wrong amount
completion(INCurrencyAmountResolutionResult.unsupported())
return
}
if let currencyCode = currencyAmount.currencyCode {
if let _ = EnumCurrency(rawValue: currencyCode) { // we found currency code that we know
completion(INCurrencyAmountResolutionResult.success(with: INCurrencyAmount(amount: NSDecimalNumber(value: abs(amount.doubleValue)), currencyCode: currencyCode)))
return
}
}
// if we are here so we don't have proper currency, try to offer user to choose the same amount but with all possible currencies
let disambiguationArray: [INCurrencyAmount] = EnumCurrency.allValues.map({ (currency) -> INCurrencyAmount in
return INCurrencyAmount(amount: NSDecimalNumber(value: abs(amount.doubleValue)), currencyCode: currency.rawValue)
})
completion(INCurrencyAmountResolutionResult.disambiguation(with: disambiguationArray))
}
}
else { // we don't have value
completion(INCurrencyAmountResolutionResult.needsValue())
}
}
enum EnumCurrency : String {
case EUR = "EUR"
case USD = "USD"
static let allValues = [EUR, USD]
}
Обновление: как воспроизвести (согласно вопросу Дэвида):
1) создать новое намерение расширения
2) в файле plist оставьте только один тип намерения: http://take.ms/pt16N
3) Ваш класс IntentHandler (будет создан xCode) должен подтвердить протокол INSendPaymentIntentHandling.
4) В классе IntentHandler добавьте следующее:
func resolveCurrencyAmount(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INCurrencyAmountResolutionResult) -> Void) {
if let currencyAmount = intent.currencyAmount { // need to check if we have proper value
if let amount = currencyAmount.amount {
if amount.doubleValue == 0 { // wrong amount
completion(INCurrencyAmountResolutionResult.unsupported())
return
}
if let currencyCode = currencyAmount.currencyCode {
if let _ = EnumCurrency(rawValue: currencyCode) { // we found currency code that we know
completion(INCurrencyAmountResolutionResult.success(with: INCurrencyAmount(amount: NSDecimalNumber(value: abs(amount.doubleValue)), currencyCode: currencyCode)))
return
}
}
// if we are here so we don't have proper currency, try to offer user to choose the same amount but with all possible currencies
let disambiguationArray: [INCurrencyAmount] = EnumCurrency.allValues.map({ (currency) -> INCurrencyAmount in
return INCurrencyAmount(amount: NSDecimalNumber(value: abs(amount.doubleValue)), currencyCode: currency.rawValue)
})
completion(INCurrencyAmountResolutionResult.disambiguation(with: disambiguationArray))
}
}
else { // we don't have value
completion(INCurrencyAmountResolutionResult.needsValue())
}
}
enum EnumCurrency : String {
case EUR = "EUR"
case USD = "USD"
static let allValues = [EUR, USD]
}
// MARK: - Confirm
func confirm(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Void) {
// success
completion(INSendPaymentIntentResponse(code: INSendPaymentIntentResponseCode.success, userActivity: nil))
}
// MARK: - Handle
func handle(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Void) {
// just for test
completion(INSendPaymentIntentResponse(code: .failureRequiringAppLaunch, userActivity: userActivity))
}
5) И вы можете запустить с Siri: вы увидите, что если вы выберете китайскую валюту или любую другую нестандартную валюту, а затем я в коде заставлю вас выбрать между EUR и USD, но после этого в функции RESOLVE (вызываемой, когда siri хочет разрешите валюту на большее время), вы получите китайскую валюту (поэтому вам не нужно добавлять какой-либо код для кнопок, как просил Дэвид, потому что весь интерфейс кнопок будет предоставлен Siri)
Button
или любого другого элемента, который требует взаимодействия с пользователем. - person David Seek   schedule 02.11.2016