将保存的上下文从AppDelegate加载到另一个ViewController

时间:2017-04-08 05:22:43

标签: ios json swift core-data

我试图从我的Viewcontroller中创建一个等于我的核心数据保存的对象的数组。我使用核心数据并创建了一个名为Pokemon的实体,它有3个属性 name id 和的 即可。在app委托中,我使用以下函数从此API获取Pokemon。这就是我解析数据并保存上下文的方法:

 typealias DownloadCompleted = () -> ()
 var pokemonId: Int16 = 0

func fetchPokemon(url: String, completed: @escaping DownloadCompleted) {
    let context = coreData.persistentContainer.viewContext

    let url = URLRequest(url: URL(string: url)!)

    let task = URLSession.shared.dataTask(with: url) { (data, repsonse, error) in
        if error != nil {
            print(error!)
        }

        do {

            let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
            let jsonArray = jsonResult.value(forKey: "results") as! [[String: Any]]
            for pokemonData in jsonArray {
                self.pokemonId += 1

                if self.pokemonId > 721 {

                    self.coreData.saveContext()
                    return
                }

                guard let name = pokemonData["name"] as? String else {
                    return
                }

                let pokemon = Pokemon(context: context)
                pokemon.name = name
                pokemon.id = self.pokemonId
                print("Name: \(pokemon.name) Id:\(self.pokemonId)")

                if self.pokemonId <= 151 {
                    pokemon.generation = 1
                } else if self.pokemonId <= 251 {
                    pokemon.generation = 2
                }  else if self.pokemonId <= 386 {
                    pokemon.generation = 3
                } else if self.pokemonId <= 493 {
                    pokemon.generation = 4
                } else if self.pokemonId <= 649 {
                    pokemon.generation = 5
                } else if self.pokemonId <= 721 {
                    pokemon.generation = 6
                }

            }



            guard let nextURL = jsonResult.value(forKey: "next") as? String else {
                self.coreData.saveContext()
                return
            }

            DispatchQueue.main.async {
                self.fetchPokemon(url: nextURL, completed: { 
                    self.coreData.saveContext()
                })
                completed()
            }

        } catch let err {
            print(err.localizedDescription)
        }



    }
    task.resume()

}

这就是我在appDelegate中调用它的方式。真的不知道在fetchPokemon中间做什么或如何在另一个视图控制器中调用它。所以我把它留空了,不确定这是否与我遇到的问题有关。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let context = self.coreData.persistentContainer.viewContext
    let pokemonListVC = self.window?.rootViewController as! PokemonListVC
    pokemonListVC.context = context
    fetchPokemon(url: pokemonAPI) {

    }
    return true
}

我正在使用app store中的这个SQL-Light只读应用程序。我检查数据,所有721口袋妖怪都在保存。现在,我不知道如何使我的视图控制器中的数组等于所有721口袋妖怪保存。我将此代码添加到我的viewController中。

class PokemonListVC: UIViewController {

  weak var context: NSManagedObjectContext! {
      didSet {
        return pokemon = Pokemon(context: context)
      }
  }
  var pokemon: Pokemon? = nil
  lazy var pokemons = [Pokemon]()
  override func viewDidLoad() {
      super.viewDidLoad()
      loadData()
  }

  func loadData() {
    pokemons = pokemon!.loadPokemon(generation: 1, context: context)
  }
}

我已经创建了我的Pokemon实体的扩展,并添加了一个函数loadPokemon,可以按代过滤Pokemon。这是代码。

extension Pokemon {

func loadPokemon(generation: Int16 = 0, context: NSManagedObjectContext) -> [Pokemon] {
    let request: NSFetchRequest<Pokemon> = Pokemon.fetchRequest()
        request.predicate = NSPredicate(format: "generation = %@", generation)
        request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        do {
            let pokemons = try context.fetch(request)
            print("My Pokemon count: \(pokemons.count)")
            return pokemons
        } catch let err {
            print(err.localizedDescription)
        }
    return []
}

}

当我在ViewController中调用loadData时,它会崩溃。数组计数为0,因此是英雄扩展中的数组。所以我不知道如何使我的数组等于从coreData保存的Pokemon。

非常感谢提供的任何帮助。 :)

这是我的deleteRecords代码,它也在我的appDelegate中。这将删除应用程序启动时的所有记录。我在fetchPokemons之前的didFinishLaunchingWithOption函数的最开始调用此方法。

func deleteRecords() {
    let context = coreData.persistentContainer.viewContext
    let pokemonRequest: NSFetchRequest<Pokemon> = Pokemon.fetchRequest()

    var deleteRequest: NSBatchDeleteRequest
    var deleteResults: NSPersistentStoreResult

    do {
        deleteRequest = NSBatchDeleteRequest(fetchRequest: pokemonRequest as! NSFetchRequest<NSFetchRequestResult>)
        deleteResults = try context.execute(deleteRequest)
    } catch let err {
        print(err.localizedDescription)
    }

}

1 个答案:

答案 0 :(得分:0)

正如您所说,您确定所有的pockemon记录都已正确存储在您的coredata中,您只需通过提取获取请求即可从您的codedata中获取记录。我已经为联系人存储创建了演示,我可以通过此获取请求获得所有联系人,您可以在ViewController中尝试使用此代码来获取所有记录。

 let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject> (entityName: "Pokemon")

    do {
        arrPockemon = try managedContext.fetch(fetchRequest)

    }catch let error as NSError {
        showAlert(string: error.localizedDescription)
    }

尝试先获取所有记录,如果你得到所有记录,那么就可以进行过滤扩展和所有记录。希望它会对你有所帮助。你可以在这里学习https://code.tutsplus.com/tutorials/core-data-and-swift-core-data-stack--cms-25065

在userDefault上保存标志。

 //check for first time when app is installed first time(first time flag is not present so)
    let userDefault = UserDefaults.standard.dictionaryRepresentation()
    if userDefault.keys.contains("isDataAvailable") {
        //key is availebe so check it
        if userDefault["isDataAvailable"] as! String == "1"{
            //no need to call server for data
        }else{
            //fetch data from server
            // once you get data from server make isDataAvailable flage as 1
            UserDefaults.standard.setValue("1", forKey: "isDataAvailable")
            UserDefaults.standard.synchronize()
        }
    }
    else{
        //flag is not avalable so call server for data
        // once you get data from server make isDataAvailable flage as 1
        UserDefaults.standard.setValue("1", forKey: "isDataAvailable")
        UserDefaults.standard.synchronize()
    }