2016-01-04 152 views
0

因此,我正在为iOS创建货币跟踪器。目前我已经设法提取跟踪器的API并将其作为我的Main.storyboard上的不错标签呈现。当我尝试运行我的应用程序时,我获得最新货币值,但几分钟后不会使用新数据自行刷新。我的问题是,如何让应用程序每分钟都能刷新一次,因此用户可以始终使用货币值进行更新。如何自动更新应用程序iOS应用程序

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() 
    } 




} 

非常感谢

+1

欢迎来到“堆栈溢出”我很愿意帮你这个问题,但首先我需要知道你在哪里查询这些信息。也许尝试编辑您的帖子并插入您用于查询信息的代码并告诉我们它位于何处。谢谢! – Jaba

回答

1

要更新定期的数据(如每分钟,如你所提到的),你会想使用一个NSTimer。它们允许您在每次指定的时间已过时运行一个函数。

let updateTimer = NSTimer.scheduledTimerWithTimeInterval(TIME_BETWEEN_CALLS, target: self, selector: Selector("FUNCTION"), userInfo: nil, repeats: true); 
  • TIME_BETWEEN_CALLS意味着你的更新功能的调用之间的秒数。

  • FUNCTION指定由定时器调用哪个函数。

  • 如果你想在某个时候停止自动更新,请拨打updateTimer.invalidate()

Here's some more information about timers I found to be quite useful.

+0

我的代码在部件选择器上应该如何显示:选择器(?) 感谢您的帮助 –

+0

您需要您想调用的函数的名称。如果你有一个更新例程'func update(){}',那么在定时器定义中,你将不得不放置'selector:Selector(“update”)' – ArdiMaster

+0

嗨。不幸的是,在时间间隔结束后,我仍然收到很大的错误信息。它说: '2016-01-05 00:46:36.600 Bitfo [22124:1699411] - [Bitfo.ViewController getJSON]:无法识别的选择器发送到实例0x608000100090 2016-01-05 00:46:36.601 Bitfo [22124 :1699411] - [Bitfo.ViewController getJSON]:无法识别的选择器发送到实例0x608000100090 2016-01-05 00:46:36.603 Bitfo [22124:1699411]' –

3

假设你想从API每次你的视图控制器被加载时间获取您的值(当应用程序启动时,当应用从后台重新开始),你应该叫您的视图控制器上的viewWillAppear方法内的异步API方法。每当视图即将显示时,viewWillAppear就会被调用。您还可以查看其他视图生命周期方法以确定何时是重新加载数据的最佳时间。

override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 

    updateCurrencyDataAsync() //Your API method call 
}