Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import Foundation
- class ViewController: UIViewController, CurrencyViewControllerDelegate {
- var toPass:String!
- @IBOutlet weak var USD: UITextField!
- @IBOutlet weak var BTC: UILabel!
- @IBAction func BackgroundTapped(sender: AnyObject) {
- USD.resignFirstResponder()
- calculate()
- }
- //var bitcoinPrice:Int = 0
- @IBOutlet weak var currencySelector: UIButton!
- @IBAction func refreshedPressed(sender: AnyObject) {
- update()
- BTC.text = "1"
- }
- override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
- if (segue.identifier == "presentCurrency") {
- var currencyVC = segue.destinationViewController as CurrencyViewController
- currencyVC.delegate = self;
- }
- }
- func currencyViewControllerDidSelect(value: String) {
- currencySelector.setTitle(value, forState: UIControlState.Normal)
- update()
- BTC.text = "1"
- //do your stuff here
- }
- struct price {
- static var BTCprice: Double = 0
- }
- func handler(response: NSURLResponse!, data : NSData!, error : NSError!) {
- if ((error) != nil) {
- println("There was a primary error internet")
- BTCFallback()
- } else if (NSString(data:data, encoding:NSUTF8StringEncoding)) == nil {
- BTCFallback()
- println("Handler chose to fallback as nil")
- } else if (NSString(data:data, encoding:NSUTF8StringEncoding)) == "" {
- //USD.text = "Fetching...";
- println("func handler set usd to fetching" + " = true")
- BTC.text = "1.0"
- println("Handler chose to fallback as blank")
- BTCFallback()
- } else {
- println("Handler found no issues with: " + (NSString(data:data, encoding:NSUTF8StringEncoding))!)
- setUSDText((NSString(data:data, encoding:NSUTF8StringEncoding))!, sender: "handler")
- //self.USD.text = (NSString(data:data, encoding:NSUTF8StringEncoding))
- println("handler called function set")
- var localPrice = (NSString(data:data, encoding:NSUTF8StringEncoding))?.integerValue
- var doublePrice:Double = Double(localPrice!)
- price.BTCprice = doublePrice
- println("Handler set price.btcprice as " + "\(doublePrice)")
- }
- }
- func fallback(response: NSURLResponse!, data : NSData!, error : NSError!) {
- if ((error) != nil) {
- println(error)
- self.USD.text = "No Internet"
- self.BTC.text = "No Internet"
- var alert = UIAlertController(title: "API Error", message: "The BitPay API could not be reached. Either it is down, or CryptoCalc can't reach it. Ensure that your phone is connected to the internet, and that this app is not being blocked access, or try again later.", preferredStyle: UIAlertControllerStyle.Alert)
- alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
- self.presentViewController(alert, animated: true, completion: nil)
- self.USD.text = "No Internet"
- self.BTC.text = "No Internet"
- } else {
- if (NSString(data:data, encoding:NSUTF8StringEncoding) == "") {
- self.USD.text = "API Error"
- self.BTC.text = "API Error"
- var alert = UIAlertController(title: "API Error", message: "The BitcoinAverage Price Index didn't give a response. Either it's down, or you made too many requests and it blocked you. Only use the refresh button as needed, as it refreshes automatically. Try again later.", preferredStyle: UIAlertControllerStyle.Alert)
- alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
- self.presentViewController(alert, animated: true, completion: nil)
- self.USD.text = "API Error"
- self.BTC.text = "API Error"
- } else {
- var data = NSData(data: data);
- // let value = NSString(string: USD.text).doubleValue / NSString(data:data, encoding:NSUTF8StringEncoding).doubleValue!
- // Define JSON string
- var JSONString = "\(data)"
- // Get NSData using string
- if let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
- // Parse JSONData into JSON object
- var parsingError: NSError?
- if let JSONObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parsingError) as? [String: AnyObject] {
- // If the parsing was successful grab the rate object
- var rateObject: AnyObject? = JSONObject["rate"]
- // Make sure the rate object is the expected type
- if let rate = rateObject as? Double {
- println("BITPAY got " + "\(rate)")
- //self.USD.text = "\(rate)"
- setUSDText("\(rate)", sender: "fallback")
- println("Bitpay set USD.text as" + "\(rate)")
- var localPrice2 = rate
- price.BTCprice = localPrice2
- println("Bitpay set price.BTCPrice as" + "\(localPrice2)")
- BTC.text = "1.0"
- }
- } else {
- // There was an error parsing the JSON data
- println("Error parsing JSON: \(parsingError)")
- BTC.text = "err1"
- }
- }
- // println("async fetch: " + price);
- // self.USD.text = price
- // bitcoinPrice = (price).integerValue
- }
- }
- }
- func setUSDText(price: String, sender: String) {
- USD.text = price
- USD.textAlignment = NSTextAlignment.Center
- BTC.text = BTC.text
- println("setUSDTEXT set USD.text was set as" + "\(price)" + "by " + sender)
- }
- func BTCFallback(){
- var string2 = currencySelector.currentTitle
- var url = NSURL(string:"https://bitpay.com/api/rates/" + (string2)!)
- var request = NSURLRequest(URL: url!)
- NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:fallback)
- }
- // USD.text = NSString(data:data, encoding:NSUTF8StringEncoding)
- //BTC.text = "\(value)"
- // println("Normal fetch!")
- override func viewDidLoad() {
- currencySelector.setTitle("USD", forState: UIControlState.Normal)
- super.viewDidLoad()
- BTC.textAlignment = NSTextAlignment.Center
- self.update(); //it will call update immediately
- var timer = NSTimer.scheduledTimerWithTimeInterval(120, target: self, selector: Selector("update"), userInfo: nil, repeats: true) //repeats after 2minutes
- }
- func getBTCPrice() {
- /*// if (USD.text).toInt() != bitcoinPrice {
- let string1 = "https://api.bitcoinaverage.com/ticker/"
- var string2 = currencySelector.currentTitle
- let string3 = "/last"
- println("https://api.bitcoinaverage.com/ticker/\(string2)\(string3)")
- var alert = UIAlertController(title: "API Error", message: "www.api.bitcoinaverage.com/ticker/" + (string2)! + "/last", preferredStyle: UIAlertControllerStyle.Alert)
- alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
- self.presentViewController(alert, animated: true, completion: nil)
- */
- var string2 = currencySelector.currentTitle
- var url = NSURL(string:"https://api.bitcoinaverage.com/ticker/global/" + (string2)! + "/last")
- println(url)
- var request = NSURLRequest(URL: url!)
- NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:handler)
- }
- func update() {
- //USD.text = "Fetching...";
- println("func update set usd to fetching" + " = true")
- BTC.text = "1.0"
- getBTCPrice()
- USD.textAlignment = NSTextAlignment.Center
- println("BTCAV")
- }
- func calculate() {
- let value = NSString(string: USD.text).doubleValue / (price.BTCprice)
- let roundedval = (round(100000000 * value) / 100000000)
- BTC.text = "\(roundedval)"
- BTC.textAlignment = NSTextAlignment.Center;
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement