在昨天做完Day16:用If...else做一款猜數字遊戲 後 , 今天我們來講一下如何用學過的
If....eles做一個匯率兌換App,方便日後我們出國時購買商品時去計算所花費用划不划算
實做步驟:
1.打開Xcode , 建立新的專案
2.按+新增Slider , Label , TextField , ImageView , UIPickView.......
3.到第三方網站申請試用,即可取得即時匯率,並把使用呼叫
第三方匯率API的網址貼入Swift Code
4.使用第三方API網站取得即時匯率,取得的檔案為JSON檔,再用這個檔案的匯率即時轉換
5.撰寫程式邏輯
override func viewDidLoad() {
super.viewDidLoad()
URLSession.shared.dataTask(with: NSURL(string: "http://apilayer.net/api/live?access_key=yourkey¤cies=EUR,TWD,CNY,JPY,HKD,KRW&source=USD&format=1")! as URL, completionHandler: { (data, response, error) -> Void in
// Check if data was received successfully
if error == nil && data != nil {
do {
// Convert NSData to Dictionary where keys are of type String, and values are of any type
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
// Access specific key with value of type String
let dict = json["quotes"] as! NSDictionary
for (key, value) in dict {
let myKey = key as! String
let index = myKey.index(myKey.startIndex, offsetBy: 3)
self.pickData.append(String(myKey.suffix(from: index)))
self.pickDict[String(myKey.suffix(from: index))] = value as? Double
}
} catch {
// Something went wrong
}
}
}).resume()
6.執行iPhone 11 Pro Max模擬器執行換匯App