Reputation: 29084
I am trying to make a currency converter in Swift. I saw this post: Need API for currency converting and How to make an HTTP request in Swift?.
So when I combined them together:
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()
It returns me a output as such:
Optional("USD to EUR",0.7987,"11/20/2014","3:45am")
But I want to access the currency exchange rate. How do I do that? I am not sure how to do that?
Upvotes: 1
Views: 8309
Reputation: 1542
I've made a simpler currency converter in Swift 5. If you're interested, check it out in my GitHub: https://github.com/ThiagoAM/CurrencyConverter
The usage is really simple:
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!) •••")
})
}
}
If you want to learn how to make it, you can study the Swift code here: https://github.com/ThiagoAM/CurrencyConverter/blob/master/CurrencyConverter.swift
It's basically a XML parser that fetches the data from the following source: https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
Upvotes: 6
Reputation: 1233
Swift 3 version: I had trouble getting the accepted answers to compile in Swift 3. Here is what I was able to get to work in 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()
Upvotes: 1
Reputation: 23078
The data returned is a string where the values are separated by commas, so this would be my approach:
var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
let values = dataString.componentsSeparatedByString(",")
let exchangeRate = values[1].doubleValue
Upvotes: 1
Reputation: 4823
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
let exchangeRate = string.componentsSeparatedByString(",")[1].doubleValue
}
Upvotes: 2