我正在从API
获取json数据,并从其中填充UITableview
-到目前为止,一切工作正常。
问题是将数据保存到核心数据中。据我所知-我正确地保存了数据,并且进行调试以查看实际上已将15个对象保存到核心数据中。我的问题是当尝试从核心数据取回数据时-我从整个json列表中仅获得一个对象,通常它是第一个对象,但有时是其他索引。
这是我的VC:
import UIKit
import CoreData
import Kingfisher
class MoviesViewController: UITableViewController {
let base_url = "https://api.androidhive.info/json/movies.json"
let context = PersistanceService.context
var moviesArray = [Movie]()
override func viewDidLoad() {
super.viewDidLoad()
if loadData(){
print("loading items from local presistancy")
} else {
print("fetching new data from api")
dataFetchFromMoviesApi()
}
//dataFetchFromMoviesApi()
tableView.estimatedRowHeight = 180
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "MovieCell")
}
//MARK: - TableView Delegate Method
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "showMovieDetails", sender: moviesArray[indexPath.row])
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
//MARK: - TableView Datasource Methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let movie = moviesArray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! TableViewCell
cell.title.text = "Title: \(movie.title)"
cell.rating.text = "Rating: \(String(movie.rating))"
cell.releaseYear.text = "Release Year: \(String(movie.releaseYear))"
cell.genre.text = "Genre: \(String(movie.genre[0]))"
cell.movieImage.downloaded(from: movie.image)
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return moviesArray.count
}
//MARK: - Segue Method
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMovieDetails" {
let movieVC = segue.destination as! MovieDetailsViewController
movieVC.selectedMovie = sender as? Movie
}
}
//MARK: - Data Fetching Method
func dataFetchFromMoviesApi(){
httpRequest(urlForRequest: base_url) { [weak self] (data: Data?, error: Error?) in
if error == nil { //no error - continue
if let moviesData = data { //un-wrapping the data object
let decoder = JSONDecoder()
do {
let responseArray = try decoder.decode([Movie].self, from: moviesData)
//print(responseArray)
DispatchQueue.main.async {
self?.moviesArray = responseArray
self?.moviesArray.sort(by: {$0.releaseYear > $1.releaseYear})
for movie in self!.moviesArray {
let movieModel = MovieModel(context: self!.context)
movieModel.title = movie.title
movieModel.releaseYear = String(movie.releaseYear)
movieModel.rating = String(movie.rating)
movieModel.genre = movie.genre[0]
movieModel.image = movie.image
}
PersistanceService.saveContext()
self?.tableView.reloadData()
}
} catch {
print(error)
}
}
} else {
//error fetching data
print(error?.localizedDescription ?? "error with no description")
}
}
}
//MARK: - Http Request
private func httpRequest(urlForRequest: String, completion: @escaping (Data?, Error?) -> Void){
guard let url = URL(string: urlForRequest) else {return}
let task = URLSession.shared.dataTask(with: url) { (data: Data?, urlResponse: URLResponse?, error: Error?) in
if error == nil {
//task was succfull
completion(data, nil)
} else {
//task was unsuccessfull
completion(nil, error)
}
}
task.resume()
}
func saveData(){
do {
try context.save()
} catch {
print("error saving context, \(error.localizedDescription)")
}
}
func loadData() ->Bool{
let fetchRequest: NSFetchRequest<MovieModel> = MovieModel.fetchRequest()
do {
let movies = try PersistanceService.context.fetch(fetchRequest)
print(movies.count)
for movie in movies {
let title = movie.title!
let rating = Float(movie.rating!)!
let image = movie.image!
let genre = [movie.genre!]
let releaseYear = Int(movie.releaseYear!)!
let newMovie = Movie(title: title, image: image, rating: rating, releaseYear: releaseYear, genre: genre)
self.moviesArray.append(newMovie)
print("movies array count: \(moviesArray.count)")
print("successfully loaded items")
return true
}
} catch {
print("error fetching from core data, \(error)")
return false
}
return false
}
}
我正在使用2种并行数据类型-一种是用于核心数据的电影实体,另一种是符合可编码协议的电影结构,另一种用于解码json。因此,当取回获取请求时,我将其分配给movie对象,并且据我了解,该请求使movie对象成为我的movie实体的数组。我说的对吗?
希望有人可以指出我的错误。
答案 0 :(得分:1)
您已将退货放在loadData
的错误位置,将其移出for
循环
for movie in movies {
let title = movie.title!
let rating = Float(movie.rating!)!
let image = movie.image!
let genre = [movie.genre!]
let releaseYear = Int(movie.releaseYear!)!
let newMovie = Movie(title: title, image: image, rating: rating, releaseYear: releaseYear, genre: genre)
self.moviesArray.append(newMovie)
print("movies array count: \(moviesArray.count)")
print("successfully loaded items")
// return true <-- This was wrong
}
return true //move it here