Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-repeat function in swift

Tags:

ios

swift

nstimer

I'm creating an app for iOS devices which will monitor price of one stock. I've successfully created a function which collets the data from an API and prints out the current value of stock.

The problem is that when I run the app one (current) price gets printed and it stays like that all the time.

My question is how do I make that function repeat itself every specified amount of time?

This is my viewDidLoad and is the function I want to repeat every couple of seconds.

Code:

import Cocoa
class ViewController: NSViewController {
let baseURL = "url"
@IBOutlet weak var bitcoinValue: NSTextField!
override func viewDidLoad() {
    super.viewDidLoad()
        getJSON { (usdPrice) -> Void in
            let usdPriceText = usdPrice.description
            self.bitcoinValue.stringValue = usdPriceText 
            print(usdPrice)   
        }  
}
func getJSON(completion: (Double) -> Void) {
    let url = NSURL(string: baseURL)
    let request = NSURLRequest(URL: url!)
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error == nil{
            let swiftyJSON = JSON(data: data!)
            let usdPrice = swiftyJSON["bpi"]["USD"]["rate"].doubleValue
            completion(usdPrice)
        } else {
            print("There was an error!")
        }
    } 
    task.resume()
    }
}
like image 368
Anton N Avatar asked Jul 18 '26 10:07

Anton N


1 Answers

You can use NSTimer.

following is a example

//in your viewdidload
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)


// must be internal or public. 
func update() {
// your repeating function
}
like image 90
Ratul Sharker Avatar answered Jul 21 '26 01:07

Ratul Sharker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!