Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto update UI when app is opened

Tags:

swift

I have successfully been able to get my weather app working; displaying the current test data and so forth. But the only issue now is I can only get the app to fetch the data by pressing my "Refresh" button I made. How can I make my app update the UI when it is opened?

Here is my working code:

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

}
    }

What I was looking at says to use the AppDelegate.swift file and its built in func "func applicationDidEnterBackground(application: UIApplication)" but everything I try either breaks the app or just does not work. I want to have the app run the getTemp function, getHumid function and then update the UI with the values like I did in the IBAction functions from the buttons.

Any help is greatly appreciated.

EDIT:

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

Attempted adding the second solution, was not able to run with deinit().

like image 753
MicrosoftDave Avatar asked Apr 17 '15 22:04

MicrosoftDave


2 Answers

The standard trick to get an app to do something every time it's opened is to store a date in NSUserDefaults the first time the app is opened and then to check the stored date against the current date when the app is opened again. If enough time has passed, you do the deed, otherwise you don't. If you do the deed, then you store the current date back into NSUserDefaults to start a new period.

like image 160
wltrup Avatar answered Nov 12 '22 18:11

wltrup


1st solution: You can use notifications for that, in your viewcontroller add this to viewDidLoad:

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

    getHumid()
    getTemp()

}

2nd solution: alternatively in viewDidLoad:

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

and a new function to the viewController

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

in both cases you will need to override denit (this prevents the observations to be called when the viewcontroller is deallocated.

deinit {
   NSNotificationCenter.defaultCenter().removeObserver(self)
}
like image 43
Sebastian Flückiger Avatar answered Nov 12 '22 19:11

Sebastian Flückiger