简体   繁体   中英

How to refresh or reload app data in swift 2

I wrote and app in swift which it has a view controller which I change some settings in it, for example : all view controllers labels and titles will change. but my problem is when I change the app settings which I store them in core data and I use navigation bar button to get back to the parent view controller when I fetch from core data I get nothing still the same data! but settings view controller when I go to it again it loads the right data! And if I close the app and reopen it, the app loads the correct data! So my question is how can I reload or relaunch the first view controller or entire app programmatically ?

for better understanding of my question below is my parent view controller which contains navigation bar.

Code :

import UIKit
import AVKit
import AVFoundation
import CoreData

class playVideo: UIViewController {

    //data source
    var languageDB = [NSManagedObject]()
    let managedContext = AppDelegate().managedObjectContext

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.hidesBackButton = true
        change_language()
    }

  override func viewDidLayoutSubviews() {
        self.view.setNeedsDisplay()
    }



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



    func change_language(){
        Insert("فارسی")//insert default language
        fetch("Language")
        let Language = languageDB[0]
        let row_value : String = Language.valueForKey("lang") as! String

        if(row_value == "فارسی"){
            self.navigationItem.title = "پخش زنده تصاویر از حرم مطهر رضوی"
            self.navigationItem.backBarButtonItem?.title = "صفحه اصلی"
        }else if(row_value == "English"){
            self.navigationItem.title = "Live broadcast from razavi holy shrine"
            self.navigationItem.backBarButtonItem?.title = "Main Page"
        }else if(row_value == "العربية"){
            self.navigationItem.title = "لايف صور من مقام رضوي"
            self.navigationItem.backBarButtonItem?.title = "صفحةابتدائي"
        }
    }


    //Insert Function
    func Insert(lang : String) {
        let check_empty = entityIsEmpty("Language")
        if(check_empty != true){

            let saveLanguage = NSEntityDescription.insertNewObjectForEntityForName("Language", inManagedObjectContext: managedContext)

            // add our data
            saveLanguage.setValue(lang, forKey: "lang")

            //2
            do {
                try managedContext.save()
                //3
                languageDB.append(saveLanguage)

            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            }


        }//end of check empty if
    }

    //fetch Functions
    func fetch(entity: String){
        let langfetch = NSFetchRequest(entityName: entity)

        do{
            let results = try managedContext.executeFetchRequest(langfetch)
            languageDB = results as! [NSManagedObject]

        }catch{
            fatalError("bad things happend \(error)")
        }

    }

    //check entity is empty Function
    func entityIsEmpty(entity: String) -> Bool
    {

        let request = NSFetchRequest(entityName: entity)

        do{
            let results = try managedContext.executeFetchRequest(request)
            languageDB = results as! [NSManagedObject]

        }catch{
            fatalError("Cant handel entity \(error)")
        }

        if languageDB.count != 0
        {
            return true
        }
        else
        {
            return false
        }


    }


    func Refresh() {
        // Do some reloading of data and update the table view's data source
        // Fetch more objects from a web service, for example...

        self.dismissViewControllerAnimated(true, completion: nil)
        self.navigationController!.dismissViewControllerAnimated(true, completion: nil)
        navigationController!.popViewControllerAnimated(true)
        self.navigationItem.hidesBackButton = true
        change_language()
    }

}

Try renew your app view controller instead or reload or relaunching the app

 func reNew(){
        //reload application data (renew root view )
        UIApplication.sharedApplication().keyWindow?.rootViewController = storyboard!.instantiateViewControllerWithIdentifier("Root_View")
    }

Root_View is the view controller which you want it to renew, you can set identifier for your view controllers in identity inspector.

To access your app delegate, you shouldn't create a new one with AppDelegate() , but instead you should get a reference to the current one. You can do this with

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

Edit: Having said that, I really wouldn't use Core Data for a task like this. You're much better off using NSUserDefaults .


Try this one

If your are successfully inserted and fetching data from Core data, you should put you function call
change_language() in viewWillAppear() method and remove refresh() method

It may help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM