如何推送不在导航控制器中的View Controller?斯威夫特

时间:2019-12-16 19:54:07

标签: ios json swift xcode

我有两个ViewController,TimeZonesTableResultsTableController

TimeZonesTable包含一个搜索栏。搜索结果显示在ResultsTableController中。

点击ResultsTableController中的结果会将时区保存到Core Data,并(应)关闭ResultsTableController并重新加载TimeZonesTable,以显示所有已保存的时区。

关闭TimeZonesTable后,我无法重新加载ResultsTableController

我尝试在TimeZonesTable的{​​{1}}函数中重新加载viewWillDisappear表,但是它不起作用。

任何帮助将不胜感激。

注意:ResultsTableController不在导航控制器中。

TimeZonesTable

ResultsTableController

ResultsTableController

import UIKit
import CoreData

class TimeZonesTable: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {

    var cities: [Zone] = []
    var savedCities: [SavedCity] = [] {
        didSet {
            refreshData()
        }
    }
    var resultsTableController: ResultsTableController!

    override func viewDidLoad() {

        getSavedCities()
        getAvailableCities()

        navigationItem.leftBarButtonItem = editButtonItem
        navigationItem.leftBarButtonItem?.tintColor = UIColor.label

        resultsTableController = ResultsTableController()

        let searchController = UISearchController(searchResultsController: resultsTableController)

        searchController.searchResultsUpdater = self
        searchController.searchBar.autocapitalizationType = .none

        if #available(iOS 11.0, *) {
            // For iOS 11 and later, place the search bar in the navigation bar.
            navigationItem.searchController = searchController

            // Make the search bar always visible.
            navigationItem.hidesSearchBarWhenScrolling = false
        } else {
            // For iOS 10 and earlier, place the search controller's search bar in the table view's header.
            tableView.tableHeaderView = searchController.searchBar
        }

        searchController.delegate = self
        searchController.searchBar.delegate = self // Monitor when the search button is tapped.
        definesPresentationContext = true

    }

    func getAvailableCities() {

        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        let url = Bundle.main.url(forResource: "data", withExtension: "json")!

        let task = session.dataTask(with: url) { data, response, error in

            // Check for errors
            guard error == nil else {
                print ("error: \(error!)")
                return
            }
            // Check that data has been returned
            guard let content = data else {
                print("No data")
                return
            }

            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let fetchedData = try decoder.decode([Zone].self, from: content)

                for city in fetchedData {
                    self.cities.append(city)
                }

            } catch let err {
                print("Err", err)
            }
        }
        // Execute the HTTP request
        task.resume()
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return savedCities.count
    }

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

        if let city = savedCities[indexPath.row].cityName {

            cell.cityName.text = "\(city)"

            if let date = savedCities[indexPath.row].formattedDate {

                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-dd"
                let formattedDate = formatter.date(from: date)

                formatter.dateFormat = "EEE, d MMM yyyy"
                let dateString = formatter.string(from: formattedDate!)

                cell.cityDate.text = dateString
            }

            if let time = savedCities[indexPath.row].formattedTime {

                let formatter = DateFormatter()
                formatter.dateFormat = "HH:mm:ss"
                let formattedTime = formatter.date(from: time)

                formatter.dateFormat = "HH:mm"
                let timeString = formatter.string(from: formattedTime!)

                cell.currentCityTime.text = timeString
            }
        }
        return cell
    }

    func updateSearchResults(for searchController: UISearchController) {

        let searchBar = searchController.searchBar
        filterContentForSearchText(searchBar.text!)
    }

    // Filter results based on search text
    func filterContentForSearchText(_ searchText: String) {

        let filteredArray = cities.filter ({$0.cityName?.lowercased().range(of: searchText.lowercased()) != nil})

        resultsTableController.filteredCities = filteredArray
        resultsTableController.tableView.reloadData()
    }

    func getSavedCities() {
        if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
            if let timeZonesFromCD = try? context.fetch(SavedCity.fetchRequest()) {
                if let timeZones = timeZonesFromCD as? [SavedCity] {
                    savedCities = timeZones
                    tableView.reloadData()
                }
            }
        }
    }

    func refreshData() {

        for city in savedCities {

            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)
            let originalUrl = "http://vip.timezonedb.com/v2.1/get-time-zone?key=\(apiKey)&format=json&by=city&city=\(city.cityName!)&country=\(city.countryCode!)"

            if let encodedUrl = URL(string: originalUrl.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!) {

                let task = session.dataTask(with: encodedUrl) { data, response, error in

                    // Check for errors
                    guard error == nil else {
                        print ("error: \(error!)")
                        return
                    }
                    // Check that data has been returned
                    guard let content = data else {
                        print("No data")
                        return
                    }

                    do {
                        let decoder = JSONDecoder()
                        decoder.keyDecodingStrategy = .convertFromSnakeCase
                        let fetchedData = try decoder.decode(TimeZones.self, from: content)

                        if let data = fetchedData.zones?.first {

                            DispatchQueue.main.async {

                                // Update time and date
                                city.formatted = data.formatted
                                city.formattedTime = data.formatted!.components(separatedBy: " ").last!
                                city.formattedDate = data.formatted!.components(separatedBy: " ").first!
                                self.tableView.reloadData()

                            }
                        }
                    } catch let err {
                        print("Err", err)
                    }
                }
                // execute the HTTP request
                task.resume()
            }
        }
    }

    @IBAction func refreshButtonTapped(_ sender: Any) {
        getSavedCities()
    }
}

3 个答案:

答案 0 :(得分:0)

在此处设置一个委托,并在ResultsTableController内向其添加avaibale

resultsTableController = ResultsTableController() 
resultsTableController.delegate = self

然后

    // Save to core data
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
self.delegate?.reload()
 self.dismiss(animated: true, completion: nil)

答案 1 :(得分:0)

由于您在TimeZoneTable和ResultTable中没有不同的功能,因此我将像这样在TimeZoneTable中进行过滤:

首先添加一个新的变量:

var allCities:[Zone] = []

然后更改您的getCities以将数据复制到新的变量中

func getSavedCities() {
    if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
        if let timeZonesFromCD = try? context.fetch(SavedCity.fetchRequest()) {
            if let timeZones = timeZonesFromCD as? [SavedCity] {
                savedCities = timeZones
                allCities = timeZones
                tableView.reloadData()
            }
        }
    }
}

最后为您的SearchTextView创建文本更改的IBAction

@IBAction func searchTextViewChanged(_ sender: Any) {
    savedCities = allCities
    savedCities = savedCities.filter {
        ($0.countryName.lowercased().contains(searchTextView.text) ||
        filterString == "")
    }
    tableView.reloadData()
}

这种方法可帮助您处理重复的代码,并且您将需要更少的视图来管理,但我不知道拥有2个几乎相同的视图控制器会带来什么好处

希望这会有所帮助,即使它在技术上不完全符合您的要求,我认为这是一种更清洁的tableView过滤方法

答案 2 :(得分:0)

您可以创建协议并获取回调。请按照以下步骤操作,您将可以解决问题。

第1步:创建协议

//Step #1
protocol ResultsTableControllerDelegate {
    func didSavedTimeZone()
}

步骤2:分配代理人

import UIKit
import CoreData


class TimeZonesTable: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {
    //Your code
    var resultsTableController: ResultsTableController!

    override func viewDidLoad() {
        // Your code

        resultsTableController = ResultsTableController()

        //Step #2
        resultsTableController.resultsDelegate = self //Asign delegate here

        // Your code

    }
}

*第3步:在您的班级中实现委托,并根据需要进行任何操作*

//Step #3
extension TimeZonesTable: ResultsTableControllerDelegate {
    func didSavedTimeZone() {
        //Reload your data or Table
    }
}

第4步:在结果控制器中创建委托

import UIKit
import CoreData

class ResultsTableController: UITableViewController {

    //Step #4
    var resultsDelegate: ResultsTableControllerDelegate?

    //Your code
}

第5步:保存数据后呼叫代表

  

注意: 在解散控制器之前,请先致电代表

import UIKit
import CoreData

class ResultsTableController: UITableViewController {

    //Step #4
    var resultsDelegate: ResultsTableControllerDelegate?

    //Your code
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        //Your code
        //Step #5
        resultsDelegate?.didSavedTimeZone()
        self.dismiss(animated: true, completion: nil)
        //Your code
    }

}