Ios 如何确保每次查看viewController时都运行代码
如何让我的应用程序在每次查看应用程序时运行我的代码,而不是每次打开应用程序时运行我的代码?现在我必须退出它,然后再次打开它来运行代码 我的应用程序通过JSON提取数据并在标签中显示。我所有的代码都在viewDidLoad中 将所有代码放入ViewDidDisplay中的答案是否正确 提前谢谢 以下是全部代码:Ios 如何确保每次查看viewController时都运行代码,ios,xcode,swift,Ios,Xcode,Swift,如何让我的应用程序在每次查看应用程序时运行我的代码,而不是每次打开应用程序时运行我的代码?现在我必须退出它,然后再次打开它来运行代码 我的应用程序通过JSON提取数据并在标签中显示。我所有的代码都在viewDidLoad中 将所有代码放入ViewDidDisplay中的答案是否正确 提前谢谢 以下是全部代码: // // ViewController.swift // KitesurfioApp // // Created by Lasse Kristensen on 24/10/
//
// 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.
}
}
您需要添加
UIApplicationWilenterForeGroundNotification
并刷新您的屏幕。将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
}
你所说的“应用就是视图”到底是什么意思?我想我的意思是每次显示viewController时。这更有意义吗?抱歉,我对此有点陌生。请使用
viewWillDisplay:animated:
或viewDidDisplay:animated:
方法。在您的代码中,您提到UIApplicationIdentinterBackgroundNotification,那么我是否应该将其改为UIApplicationWillEnterForegroundNotification?无需担心。谢谢你再次为我指明了正确的方向!使用ViewWillDisplay更有意义,因为用户不必到后台刷新内容。当应用程序从后台重新运行时,ViewWillDisplay
不会被调用。Codester:虽然你的代码可以工作,但它不会更新数据。我包含了一个println(“进入前台后刷新”)来检查该部分是否执行,它确实执行了,但它似乎没有更新JSON。问题可能是JSON需要几秒钟,因此代码只使用旧值?