Git Product home page Git Product logo

pricecurrency's Introduction

PriceCurrency

Курсы валют и конвертер цен

Review

Обзор

Приложение iOS для просмотра валютных курсов и конвертации цен. Состоит из двух вкладок. На первой можно получить курс выбранной валюты в других. На второй можно конвертировать цены между двумя валютами.

Курс

Для выбора нужного курса, нужно ввести код валюты в панели и список автоматически покажется ниже.

RatePanel

Чтоб было проще ориентироваться, есть фильтр списка валют. Нажав кнопку фильтр и выделив нужные коды, список обновится и сервис покажет выбранные.

RateAndFilter

Над таблицей курсов есть таймер, который показывает давность полученных даных.

TimerRate

Реализует это сервис Exchange Rate API https://api.exchangerate.host/latest?base=rub

Конвертер валют

Пользователь вводит коды валют и цену в левой валюте. Далее происходит автоматическая конвертация цены и результат выводит под введеной ценой. Реализует это сервис Exchange Rate API https://api.exchangerate.host/convert?from=USD&to=EUR&amount=1

CoverterPanel

Под результатом приводится график динамики курса этих валют.

HistoryRateChart

Реализация

SwiftUI

Интерфейс написан на SwiftUI, он легко обноляемый при использовании предикатов.

Combine

  • Используется в интерфейсе, предикаты.

    @ObservedObject var viewModel: ConverterModel
    @State private var from: String = ""
    @State private var to: String = ""
    @State private var fromDescription: String = ""
    @State private var toDescription: String = ""
    @State private var amount: Double = 0
    @State private var lenghtSeries: CurrencySeries.Lehght = .week

  • Запросы в сеть.

    func rate(date: Date, from: String, to: [String], amount: Double) -> AnyPublisher<CurrencyRate, CurrencyError> {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let dateString = dateFormatter.string(from: date)
    let toString = to.joined(separator: ",")
    guard let url = Method.rate(date: dateString, from: from, to: toString, amount: amount).url() else {
    return Fail<CurrencyRate, CurrencyError>(error: .urlComponents)
    .eraseToAnyPublisher()
    }
    return URLSession.shared
    .dataTaskPublisher(for: url)
    .receive(on: queue)
    .map(\.data)
    .decode(type: CurrencyRate.self, decoder: decoder)
    .mapError({ error -> CurrencyError in
    switch error {
    case is URLError:
    return CurrencyError.urlError(url: url)
    default:
    return CurrencyError.response
    }
    })
    .eraseToAnyPublisher()
    }

ExchangeRateAPI

Для сервиса полкчения данных используется Exchange Rate API.

private enum Method {
///Последние базовые курсы обмена, обновляемые ежедневно.
///https://api.exchangerate.host/latest?base=rub
case rates(base: String)
///Конвертации любой суммы из одной валюты в другую.
///https://api.exchangerate.host/convert?from=USD&to=EUR&amount=1
case convert(from: String, to: String, amount: Double)
///Получить информацию о том, как валюты колеблются изо дня в день. Максимально допустимое время составляет 366 дней.
///https://api.exchangerate.host/fluctuation?start_date=2020-01-01&end_date=2020-01-04
case fluctuation(startDate: String, endDate: String)
///Исторические курсы валют вплоть до 1999 года
///Вы можете запросить у API исторические курсы, добавив дату (в формате ГГГГ-ММ-ДД)
///https://api.exchangerate.host/2020-04-04?base=USD&symbols=RUB
case rate(date: String, from: String, to: String, amount: Double)
///Ежедневная историческая ставка между двумя выбранными датами с максимальным временным интервалом 366 дней
case timeseries(start: String, end: String, base: String, currency: String)
var path: String {
switch self {
case .rates:
return "/latest"
case .convert:
return "/convert"
case .fluctuation:
return "/fluctuation"
///ГГГГ-ММ-ДД
case .rate(rate: let rate):
return "/\(rate.date)"
case .timeseries:
return "/timeseries"
}
}
var parameters: [String: String] {
switch self {
case .rates(base: let base):
return ["base" : base]
case .convert(from: let from, to: let to, amount: let amount):
return ["from": from, "to": to, "amount": String(amount)]
case .fluctuation(startDate: let startDate, endDate: let endDate):
return ["start_date": startDate, "end_date" : endDate]
case .rate(date: _, from: let from, to: let to, amount: let amount):
return ["base": from, "symbols": to, "amount": String(amount)]
case .timeseries(start: let start, end: let end, base: let base, currency: let currency):
return ["start_date": start, "end_date": end, "base": base, "symbols": currency]
}
}
func url() -> URL? {
var components = URLComponents()
components.scheme = "https"
components.host = "api.exchangerate.host"
components.path = self.path
components.queryItems = self.parameters.map() { URLQueryItem(name: $0, value: $1) }
return components.url
}
}

pricecurrency's People

Contributors

dendmitriev avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.