David Seek David Seek - 1 month ago 20
Swift Question

Swift 3 / How to call tableView.reloadData() in global function?

I'm trying to refactor a function to have it globally available. At the end of the function, a

UITableView
needs to be reloaded. I was thinking about passing the VC, but I still get


Value of type 'UIViewController' has no member 'tableView'


I know that I get that error because tableView is not part of a
UIViewController
by default, but how do I bypass it?

func downloadAvatar(_ userForAvatar: String, vc: UIViewController) {

let whereClause = "objectId = '\(userForAvatar)'"
let dataQuery = BackendlessDataQuery()
dataQuery.whereClause = whereClause

let dataStore = backendless?.persistenceService.of(BackendlessUser.ofClass())
dataStore?.find(dataQuery, response: { (users : BackendlessCollection?) in

let withUser = users?.data.first as! BackendlessUser
let imgURL = withUser.getProperty("Avatar") as? String
avatare.setValue(imgURL, forKey: userForAvatar)
vc.tableView.reloadData() // problem here

}) { (fault : Fault?) in
print("error: \(fault)")
}
}


Help is very appreciated.

Answer

Instead of have having vc: UIViewController as an argument, you should just have tv: UITableView instead. Then instead of passing the view controller, you pass it's tableView. Although if this isn't working, you could try a completion block instead.

func downloadAvatar(_ userForAvatar: String, completion: @escaping () -> ()) {

    let whereClause = "objectId = '\(userForAvatar)'"
    let dataQuery = BackendlessDataQuery()
    dataQuery.whereClause = whereClause

    let dataStore = backendless?.persistenceService.of(BackendlessUser.ofClass())
    dataStore?.find(dataQuery, response: { (users : BackendlessCollection?) in

        let withUser = users?.data.first as! BackendlessUser
        let imgURL = withUser.getProperty("Avatar") as? String
        avatare.setValue(imgURL, forKey: userForAvatar)
        completion()

    }) { (fault : Fault?) in
        print("error: \(fault)")
    }
}

Then assuming you're calling this method from the respective view controller, you can reload the tableView data within the completion block.

downloadAvatar("$uid") { [weak self] in
     self?.tableView.reloadData()
}
Comments