Home Swift 4 accessing completionhandler returned value from class variable
Reply: 1

Swift 4 accessing completionhandler returned value from class variable

user2277163
1#
user2277163 Published in 2018-02-12 22:07:02Z

Problem: I’m trying to access the value which is returned from completionHandler, to assign it to a variable which is outside the scope of completionHandler returned method. I can access the variable in the scope of the method, but I can’t from outside. I’ve tried to assign it to the class variable when I access, but didn’t work. Any ideas?

var marketler = [MarketModel]()
var marketAdiArray = [String]()

override func viewDidLoad() {
    getMarkets { (marketdizi) in
        self.objAryToTableView(markets: marketdizi)
        print(self.marketAdiArray) // -> this returns the right array
    }

    print(self.marketAdiArray) // -> this returns an empty array
 }

func getMarkets(completionHandler : @escaping ([MarketModel])->()) {
    let uid = "userID(02)"
    print("uid : \(uid)")
    MobileUserViewModel().getUser(userId: uid, completionHandler: { (user) in
// here returns an user object
        self.loginUser = user
        MarketViewModel().getMarketFromDb(mobilUser: user, completionHandler: { (marketler) in
            print("marketler : \(marketler)")
            completionHandler(marketler)
        })
    })
}

 func objAryToTableView(markets : [MarketModel]) {
    var ary = [String]()
    for m in markets {
        ary.append(m.marketName as String!)
    }
    self.marketAdiArray = ary
}
deoKasuhal
2#
deoKasuhal Reply to 2018-02-12 22:18:33Z

The code inside the block (completion handler) is getting executed after getMarketFromDb call succeeds. The code which is outside the block is executed just after the previous line where you don't have any data on the array.

If You need to trigger the UI update which updated data from data Db then you need to invoke the UI update from inside the completion block.

getMarkets { (marketdizi) in

         self.objAryToTableView(markets: marketdizi)
         print(self.marketAdiArray) // -> this returns the right array
         self.tableView.reloadData()

    }
    print(self.marketAdiArray) // -> this returns an empty array
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.438899 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO