打开应用程序时自动更新UI

时间:2015-04-17 22:45:55

标签: swift

我已经成功地让我的天气应用程序正常工作;显示当前的测试数据等。但现在唯一的问题是我只能通过按下我的“刷新”按钮来获取应用程序以获取数据。 如何让我的应用在打开时更新用户界面?

这是我的工作代码:

import Foundation
import UIKit




class ViewController: UIViewController {
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var humidLabel: UILabel!
@IBOutlet weak var refresh: UIButton!
@IBOutlet weak var negitiveSymbol: UILabel!


func getTemp(){
    var urlString = "http://torsher.ca/Weather/temperature.txt"
    var url = NSURL(string: urlString)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)){(data, response, error) in
        var urlContent = (NSString(data: data, encoding: NSUTF8StringEncoding))
        var tempContent:String = urlContent as String
        println(tempContent)

        dispatch_async(dispatch_get_main_queue()) {
            self.tempLabel.text = (tempContent)

        }
    }

    task.resume()
}

func getHumid(){
    var urlString = "http://torsher.ca/Weather/humidity.txt"
    var url = NSURL(string: urlString)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)){(data, response, error) in
        var urlContent = (NSString(data: data, encoding: NSUTF8StringEncoding))
        var humidContent:String = urlContent as String
        println(humidContent)

        dispatch_async(dispatch_get_main_queue()) {
            self.humidLabel.text = (humidContent)
        }
    }

    task.resume()
}


@IBAction func refreshPressed(sender: AnyObject, forEvent event: UIEvent) {
    getTemp()

}
@IBAction func refreshPress(sender: AnyObject, forEvent event: UIEvent) {
     getHumid()
}



        override func viewDidLoad() {
        super.viewDidLoad()

}
    }

我所看到的是说使用AppDelegate.swift文件及其内置的函数“func applicationDidEnterBackground(application:UIApplication)”但我尝试的一切都打破了应用程序或者只是不起作用。我想让应用程序运行getTemp函数,getHumid函数,然后使用我在IBAction函数中从按钮中执行的值更新UI。

非常感谢任何帮助。

修改

  //
 //  ViewController.swift
 //  WeatherStation
 //
 //  Created by on 2015-04-16.
 //  Copyright (c) 2015 . All rights reserved.
 //

 import Foundation
 import UIKit




 class ViewController: UIViewController {
 @IBOutlet weak var tempLabel: UILabel!
 @IBOutlet weak var humidLabel: UILabel!
 @IBOutlet weak var refresh: UIButton!
 @IBOutlet weak var negitiveSymbol: UILabel!
 @IBOutlet weak var dateUpdate: UILabel!


func getTemp() //Gets the temeprature from the server and displays it.
{
    var urlString = "http://torsher.ca/Weather/temperature.txt"
    var url = NSURL(string: urlString)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)){(data, response, error) in
        var urlContent = (NSString(data: data, encoding: NSUTF8StringEncoding))
        var tempContent:String = urlContent as String
        println(tempContent)

        dispatch_async(dispatch_get_main_queue()) {
            self.tempLabel.text = (tempContent)

        }
    }

    task.resume()
}

func getHumid() //Gets the humidity from the server and displays it.
{
    var urlString = "http://torsher.ca/Weather/humidity.txt"
    var url = NSURL(string: urlString)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)){(data, response, error) in
        var urlContent = (NSString(data: data, encoding: NSUTF8StringEncoding))
        var humidContent:String = urlContent as String
        println(humidContent)

        dispatch_async(dispatch_get_main_queue()) {
            self.humidLabel.text = (humidContent)
        }
    }

    task.resume() 
}


@IBAction func refreshPressed(sender: AnyObject, forEvent event: UIEvent) //Updates UI with current temperature when refresh is pressed.
{
    getTemp()
}

@IBAction func refreshPress(sender: AnyObject, forEvent event: UIEvent) //Updates UI with current humidity when refresh is pressed.
{
     getHumid()
}

func appWasOpened(notification: NSNotification!)
{
    getHumid()
    getTemp()
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(foregroundNotification)
}


override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector:        
"appWasOpened:", name: UIApplicationWillEnterForegroundNotification, object:         
nil)
    }
}

尝试添加第二个解决方案,无法使用deinit()运行。

2 个答案:

答案 0 :(得分:3)

让应用程序在每次打开时执行某些操作的标准技巧是在第一次打开应用程序时在NSUserDefaults中存储日期,然后根据应用程序的当前日期检查存储日期又开了。如果已经过了足够的时间,你就会做出行动,否则你就不会这样做。如果你做了契约,那么你将当前日期存回NSUserDefaults以开始一个新的时期。

答案 1 :(得分:2)

第一个解决方案:您可以在viewcontroller中将此通知添加到viewDidLoad

NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationWillEnterForegroundNotification, object: nil, queue: NSOperationQueue.mainQueue()) 
{ [unowned self] notification in

    getHumid()
    getTemp()

}

第二个解决方案:或viewDidLoad

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "appWasOpened:", name: UIApplicationWillEnterForegroundNotification, object: nil)

viewController

的新功能
func appWasOpened(notification: NSNotification!) 
{
    getHumid()
    getTemp()
}

在这两种情况下您将需要覆盖denit(这可以防止在取消分配视图控制器时调用观察结果。

deinit {
   NSNotificationCenter.defaultCenter().removeObserver(self)
}