使用NotificationCenter Observer处理异步请求

时间:2017-10-16 16:57:19

标签: ios swift firebase asynchronous nsnotificationcenter

有人提出类似的问题,所以我道歉,但没有一个人能够帮助我。

我正在努力通过完成处理程序将此异步请求中的值返回到Firebase。我从Firebase检索的值是一个数组,它确实存在。但是

以下是我向Firebase发出请求的功能:

class SearchManager {

    var searchResults = [String]()
    var listOfMosaics = [String]()

    // Retrieves company list from Firebase
    func getMosaicTitles(completionHandler: @escaping (_ mosaics: [String]) -> ()) {
        Database.database().reference().child("mosaics").observeSingleEvent(of: .value, with: { (snapshot) in
            guard let allMosaics = snapshot.value as? [String] else {
                print("unable to unwrapp datasnapshot")
                return
            }
            completionHandler(allMosaics)
        })
    }

    // resets search results array
    func resetSearch() {
        searchResults = []
    }

    // takes list of all mosaics and filters based on search text
    func filterAllMosaics(searchText: String) {
        searchResults = listOfMosaics.filter { $0.contains(searchText) }

    }

}

在AppDelegate中,我称之为发布通知:

    let searchManager = SearchManager()

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

    makeRootViewLaunchScreen()
    FirebaseApp.configure()
    searchManager.getMosaicTitles { (results) in
        self.searchManager.listOfMosaics = results
        NotificationCenter.default.post(name: NSNotification.Name("mosaicsReturned"), object: nil)
        self.stopDisplayingLaunchScreen()
    }
    // Adds border to bottom of the nav bar
    UINavigationBar.appearance().shadowImage = UIImage.imageWithColor(color: UIColor(red:0.00, green:0.87, blue:0.39, alpha:1.0))
    // Override point for customization after application launch.
    return true
}

func makeRootViewLaunchScreen() {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
    let viewController = mainStoryboard.instantiateViewController(withIdentifier: "launchScreen")
    UIApplication.shared.keyWindow?.rootViewController = viewController
}

// reassigns root view after Firebase request complete
func stopDisplayingLaunchScreen() {
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let viewController = mainStoryboard.instantiateViewController(withIdentifier: "centralViewController")
    UIApplication.shared.keyWindow?.rootViewController = viewController
}

在viewController的viewDidLoad中,它支持使用检索到的数组填充它的tableView,我添加了一个Notification Observer。

    var listOfMosaics = [String]()
var searchResults = [String]() {
    didSet {
        tableView.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    listOfMosaics = searchManager.listOfMosaics
    configureSearchBar()
    configureSearchBarTextField()
    self.tableView.separatorColor = UIColor(red:0.00, green:0.87, blue:0.39, alpha:1.0)

    NotificationCenter.default.addObserver(self, selector: #selector(updateListOfMosaics), name: NSNotification.Name("mosaicsReturned"), object: nil)
}

@objc func updateListOfMosaics(notification: Notification) {
    listOfMosaics = searchManager.listOfMosaics
}

但是当我调用下面的代码时,它不起作用,数组打印为空,因此它不会更新我的tableView。

extension SearchResultsTableViewController: UISearchBarDelegate {

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchManager.resetSearch()
    searchManager.filterAllMosaics(searchText: searchBar.text!)
    tableView.reloadData()
    print(listOfMosaics)
    print(searchResults)


   }
 }

先谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

这应该适合你。我认为你没有将SearchManager的实例从你的AppDelegate传递给你的ViewController。我猜你在ViewController中创建了一个新的SearchManager实例,它有一个空数组。

搜索管理器:

class SearchManager {

    var searchResults = [String]()
    var listOfMosaics = [String]()

    func getMosaicTitles(completionHandler: @escaping (_ mosaics: [String]) -> ()) {
        Database.database().reference().child("mosaics").observeSingleEvent(of: .value, with: { (snapshot) in
            guard let allMosaics = snapshot.value as? [String] else {
                print("unable to unwrapp datasnapshot")
                completionHandler([]) // <- You should include this too.
                return
            }
            completionHandler(allMosaics)
        })
    }

    func resetSearch() {
        searchResults = []
    }

    func filterAllMosaics(searchText: String) {
        searchResults = listOfMosaics.filter { $0.contains(searchText) }
    }
}

查看控制器:

class TableViewController: UITableViewController {

    var searchManager: SearchManager?
    var listOfMosaics = [String]()
    var searchResults = [String]() {
        didSet {
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        guard let searchManager = searchManager else { return }
        listOfMosaics = searchManager.listOfMosaics
        print("List of mosaics: \(listOfMosaics)")
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 0
    }

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

<强>的AppDelegate:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let searchManager = SearchManager()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)  -> Bool {
        makeRootViewLaunchScreen()
        FirebaseApp.configure()
        searchManager.getMosaicTitles { results in
            self.searchManager.listOfMosaics = results
            self.stopDisplayingLaunchScreen()
        }
        return true
    }

    func makeRootViewLaunchScreen() {
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
        let viewController = mainStoryboard.instantiateViewController(withIdentifier: "launchScreen")
        window?.rootViewController = viewController
        window?.makeKeyAndVisible()
    }

    func stopDisplayingLaunchScreen() {
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        guard let viewController = mainStoryboard.instantiateViewController(withIdentifier: "centralViewController") as? TableViewController else { return }
        let navigationController = UINavigationController(rootViewController: viewController)
        viewController.searchManager = searchManager
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
    }
}

答案 1 :(得分:0)

正如@TNguyen在评论中所说,听起来你并没有等待异步函数getMosaicTitles()完成。

您可能希望在呼叫运行时禁用搜索栏按钮,并在呼叫完成后从完成处理程序启用它。然后,在结果加载完毕之前,用户将无法单击搜索按钮。

答案 2 :(得分:0)

您可以在后台线程中从数据库中获取数据并添加完成块,以便tableView仅在获取更新的内容后重新加载。