在Swift中创建货币转换器

时间:2014-11-21 11:38:02

标签: swift

我正在尝试在Swift中制作货币转换器。我看到了这篇文章:Need API for currency convertingHow to make an HTTP request in Swift?

所以当我把它们组合在一起时:

let url = NSURL(string: "http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=nl1d1t1");

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
     println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

它返回一个输出:

Optional("USD to EUR",0.7987,"11/20/2014","3:45am")

但我想获取货币汇率。我怎么做?我不知道该怎么做?

4 个答案:

答案 0 :(得分:2)

if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
    let exchangeRate = string.componentsSeparatedByString(",")[1].doubleValue
}

答案 1 :(得分:1)

返回的数据是一个字符串,其中值以逗号分隔,因此这将是我的方法:

var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
let values = dataString.componentsSeparatedByString(",")

let exchangeRate = values[1].doubleValue

答案 2 :(得分:1)

Swift 3版本: 我无法获得在Swift 3中编译的已接受答案。以下是我能够在swift 3中工作的内容:

    guard let url = URL(string: "https://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=nl1d1t1") else {
        print("Error: cannot create translation URL")
        return
    }

    let loadRequest = URLRequest(url:url)

    URLSession.shared.dataTask(with: loadRequest, completionHandler: { (data, response, error) in
        if let error = error {
            #if DEBUG
                print("Error: data task error for translation \(error)")
            #endif
            return
        }

        guard let data = data else {
            #if DEBUG
                print("Error: data null for translation")
            #endif
            return
        }
        if let translationString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
            #if DEBUG
                print(translationString)
            #endif

            let exchangeRateArray = translationString.components(separatedBy: ",")
            let exchangeRate: Double = Double(exchangeRateArray[1])!
            print(exchangeRate)
        }
        else {
            #if DEBUG
                print("Error generating string from data in translation")
            #endif
            return
        }

    }).resume()

答案 3 :(得分:0)

我在Swift 5中制作了一个更简单的货币转换器。如果您有兴趣,请在我的GitHub中查看:https://github.com/ThiagoAM/CurrencyConverter

用法非常简单:

class ViewController: UIViewController {

// Creates the Currency Converter instance:
let currencyConverter = CurrencyConverter()

override func viewDidLoad() {
    super.viewDidLoad()

    // Updates the exchange rates:
    currencyConverter.updateExchangeRates(completion: {
        // The code inside here runs after all the data is fetched.

        // Now you can convert any currency:
        // • Example_1 (USD to EUR):
        let doubleResult = self.currencyConverter.convert(10, valueCurrency: .USD, outputCurrency: .EUR)
        print("••• 10 USD = \(doubleResult!) EUR •••")

        // • Example_2 (EUR to GBP) - Returning a formatted String:
        let formattedResult = self.currencyConverter.convertAndFormat(10, valueCurrency: .EUR, outputCurrency: .GBP, numberStyle: .decimal, decimalPlaces: 4)
        print("••• Formatted Result (10 EUR to GBP): \(formattedResult!) •••")
    })
}

}

如果您想学习如何制作它,可以在这里研究Swift代码:https://github.com/ThiagoAM/CurrencyConverter/blob/master/CurrencyConverter.swift
它基本上是一个XML解析器,可从以下来源获取数据:https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml