Created
October 9, 2014 16:26
-
-
Save ericcgu/95d17f81d658addfd207 to your computer and use it in GitHub Desktop.
This file contains 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
func convertCurrency(#localAmount:Double, localCurrency:String, foreignCurrency: String)-> Double { | |
let baseURL = NSURL(string: "http://www.freecurrencyconverterapi.com/api/v2/") | |
let query = String(localCurrency)+"_"+String(foreignCurrency) | |
let forecastURL = NSURL(string: "convert?q="+query, relativeToURL: baseURL) | |
//use a session object to manage.//like the sun | |
let sharedSession = NSURLSession.sharedSession() | |
var convertedAmount:Double = 0.0 | |
let downloadTask:NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL, completionHandler: { (location:NSURL!, response: NSURLResponse!, error: NSError!) -> Void in | |
if error == nil { | |
let dataObject = NSData(contentsOfURL: location) | |
let conversionDictionary:NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject, options: nil, error: nil) as NSDictionary | |
if let results = conversionDictionary["results"] as? NSDictionary{ | |
if let queryResults = results[query] as? NSDictionary{ | |
if let exchangeRate = queryResults["val"] as? Double{ | |
convertedAmount = (localAmount * exchangeRate) as Double | |
print(convertedAmount) | |
} | |
} | |
} | |
} | |
}) | |
downloadTask.resume() | |
return convertedAmount | |
} | |
convertCurrency(localAmount: 10, "JPY", "HKD") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment