在表格视图中显示核心数据中的数据

时间:2019-06-20 00:09:36

标签: arrays swift api uitableview core-data

我是新来的人

我的应用程序是在Flickr API中搜索并检索图像。我从API保存并在表格视图中显示。当我第一次运行我的应用程序并搜索例如“橙色”时,它表示我的搜索结果很好,而当我尝试再次搜索例如“蛋”时,它没有显示任何内容。因为我应该删除核心数据中的数据并对其进行新的搜索,但是它不起作用,但是当我关闭应用程序并再次运行它时,它显示的数据没有出现“ egg”

我正在使用MVP,该如何解决该问题

这是第一个搜索“橙色” first search

,这是第二个搜索“鸡蛋” second search

,并且在关闭应用程序并再次运行后显示“ egg”搜索 run the app again

这是我的演示者,其中包含提取方法

//MARK: - Photos delegate
protocol PhotoDataDelegate {
    func updateUI(data: [Photo])
    func noData(bool: Bool)
    func internetConnection(bool: Bool)
}


//MARK: - Photo Presenter Class

class PhotoPresenter{

    var flickrPhotoCoreData = [Photo]()
    var delegate : PhotoDataDelegate!


    //MARK: - Photos featch function
    func fetchPhotoData(searchText:String, handler: @escaping (_ status: Bool) -> ()){
        Alamofire.request(photoURL(apiKey: apiKey, textTosearchFor: searchText, page: 1, numberOfPhotos: 100)).responseJSON { (response) in
            if response.result.isSuccess {
                var data = Data()
                data = response.data!
                let decoder = JSONDecoder()
                let flickrPhotos = try? decoder.decode(FlickrResult.self, from: data)

                PresistenceService.deleteAllData("Photo")

                if flickrPhotos?.photos?.photo.isEmpty == false{
                for item in 0...(flickrPhotos?.photos!.photo.count)! - 1 {
                    let photoURL = "https://farm\((flickrPhotos?.photos?.photo[item].farm)!).staticflickr.com/\((flickrPhotos?.photos?.photo[item].server)!)/\((flickrPhotos?.photos?.photo[item].id)!)_\((flickrPhotos?.photos?.photo[item].secret)!)_m.jpg"
                    let photoID = flickrPhotos?.photos?.photo[item].id
                    let title = flickrPhotos?.photos?.photo[item].title

                    let flickrPhoto = Photo(context: PresistenceService.context)
                    flickrPhoto.id = photoID
                    flickrPhoto.title = title
                    flickrPhoto.imageURL = photoURL
                    flickrPhoto.url = URL(string: flickrPhoto.imageURL!)
                    PresistenceService.saveContext()
                    self.flickrPhotoCoreData.append(flickrPhoto)
                    //self.delegate.updateUI(data: self.flickrPhotoCoreData)
                    //print(self.flickrPhotoCoreData[item].id)
                    //print(self.flickrPhotoCoreData[item].imageURL)
                }
                } else {
                    self.delegate.noData(bool: true)
                    print("nil")
                }
                self.delegate.updateUI(data: self.flickrPhotoCoreData)
                handler(true)

            } else {
                self.delegate.internetConnection(bool: true)
                print("Can not get the data")
            }
        }
    }


}

这是我的tableViewController

import UIKit
import Kingfisher
import CoreData
class PhotoViewController: UITableViewController, UISearchBarDelegate, PhotoDataDelegate {



    @IBOutlet weak var searchBar: UISearchBar!

    var photoPresenter : PhotoPresenter!
    var dataArray = [Photo]()

    override func viewDidLoad() {
        super.viewDidLoad()
        photoPresenter = PhotoPresenter()
        photoPresenter.delegate = self


        let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
        do {
            let photo = try PresistenceService.context.fetch(fetchRequest)
            dataArray = photo
            tableView.reloadData()
        } catch {}
    }


    //MARK: - Photos search bar
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let keyword = searchBar.text
        if keyword?.isEmpty == false {
        photoPresenter.fetchPhotoData(searchText: keyword!, handler: {(finished) in
            if finished {
                self.tableView.reloadData()
                print("well done")
            }
        })
        } else {
            let alert = UIAlertController(title: "Enter text", message: "Enter text to search for", preferredStyle: .alert)
            let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        }
        self.view.endEditing(true)
    }


    //MARK: - Photos delegate functions
    func updateUI(data: [Photo]){
        dataArray = data
        tableView.reloadData()
    }

    func noData(bool: Bool) {
        if bool{
            let alert = UIAlertController(title: "No Photos", message: "No photos to show", preferredStyle: .alert)
            let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        }
    }

    func internetConnection(bool: Bool) {
        if bool{
            let alert = UIAlertController(title: "Ooops!", message: "There is no internet connection\nTry Again", preferredStyle: .alert)
            let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        }
    }



    //MARK: - Photos TableView Data
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "flickrPhotoCell", for: indexPath) as! PhotoTableViewCell

        cell.flickrPhoto.kf.indicatorType = .activity
        cell.flickrPhoto.kf.setImage(with: dataArray[indexPath.row].url)
        cell.titleOfPhotoLabel.text = dataArray[indexPath.row].title
        return cell
    }

}

这是核心数据类


class PresistenceService{


    private init() {}

    static var context: NSManagedObjectContext{
        return persistentContainer.viewContext
    }



    static var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "Flickr")
        container.loadPersistentStores(completionHandler: {
            (storeDescription, error) in
            print(storeDescription)
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    static func saveContext() {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let error = error as NSError
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        }
    }


    static func deleteAllData(_ entity: String){
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
        fetchRequest.returnsObjectsAsFaults = false

        do{
            let results = try persistentContainer.viewContext.fetch(fetchRequest)
            for object in results {
                guard let objectData = object as? NSManagedObject else {continue}
                persistentContainer.viewContext.delete(objectData)
            }
        } catch let error {
            print("Delete all data in \(Photo.self) error:", error)
        }


    }

}

0 个答案:

没有答案