如何确保每次查看viewController时都运行代码

时间:2014-10-25 07:51:05

标签: ios xcode swift

每次查看应用程序时,如何让我的应用程序运行我的代码,而不是每次都打开它?现在我必须退出它,然后再次打开它来运行代码。

我的应用程序通过JSON提取数据并将其显示在标签中。我的所有代码都在viewDidLoad中。

将所有代码放在viewDidAppear中的答案是什么?

提前致谢

以下是整个代码:

    //
//  ViewController.swift
//  KitesurfioApp
//
//  Created by Lasse Kristensen on 24/10/14.
//  Copyright (c) 2014 Lasse Kristensen. All rights reserved.
//

import UIKit
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var labelSpeed: UILabel!

    override func viewDidLoad() {


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

        // Set logo in nav bar

        navigationItem.titleView = UIImageView(image: UIImage(named: "logo"))


        refresh();
    }
    func backgroundNotification(noftification:NSNotification){

        refresh();

        println("Refreshed after background")
    }

    func refresh() {


        // Global save values

        var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate

        var context: NSManagedObjectContext = appDel.managedObjectContext!



        // JSON Fetching

        let urlPath = "http://api.openweathermap.org/data/2.5/weather?lat=55.564120&lon=12.568605"

        let url = NSURL(string: urlPath)

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
            dispatch_async(dispatch_get_main_queue(),{
                if (error != nil) {
                    println(error)
                }
                else {


                    // Delete old entries in CoreData

                    var request = NSFetchRequest(entityName: "WindData")

                    request.returnsObjectsAsFaults = false

                    var results = context.executeFetchRequest(request, error: nil)

                    for result in results! {

                        context.deleteObject(result as NSManagedObject)
                        context.save(nil)

                    }

                    // Start fetching JSON


                    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary


                    var item = jsonResult["wind"] as NSDictionary

                    var degrees:Float = item["deg"] as Float
                    var speed:Float = item["speed"] as Float


                    // Start saving JSON

                    var newItem = NSEntityDescription.insertNewObjectForEntityForName("WindData", inManagedObjectContext: context) as NSManagedObject

                    var speedValue:Float = speed as Float
                    var degreesValue:Float = degrees as Float

                    newItem.setValue(speedValue, forKey: "speed")
                    newItem.setValue(degreesValue, forKey: "degrees")

                    context.save(nil)



                }

                // Start fetching from CoreData

                var request = NSFetchRequest(entityName: "WindData")

                request.returnsObjectsAsFaults = false

                var results = context.executeFetchRequest(request, error: nil)

                if results!.count > 0 {

                    for result in results as [NSManagedObject] {


                        let degrees:Float = result.valueForKey("degrees")! as Float
                        let speed:Float = result.valueForKey("speed")! as Float


                        if speed > 6.0 {
                            self.labelSpeed.text = "Go kitesurf: \(speed) m/s \(degrees)"

                        }
                        else {
                            self.labelSpeed.text = "Stay in: \(speed) m/s \(degrees)"
                        }

                    }
                }
                else {
                    println("No data")
                }
            });
        })

        task.resume()


    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

1 个答案:

答案 0 :(得分:2)

您需要添加UIApplicationWillEnterForegroundNotification并在那里刷新您的屏幕。将viewDidLoad中的所有代码添加到辅助函数(如refreh)并在viewDidLoad时调用它或者您进入前景从背景或每当你想刷新屏幕。

override func viewDidLoad() {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgoundNofification:", name: UIApplicationWillEnterForegroundNotification, object: nil);
   //put all code of your viewDidLoad to refresh 
   refresh();
}
func backgoundNofification(noftification:NSNotification){

    refresh();
}

func refresh() {
 //here is your all code to fetch data and all

}