ios - How to change value of variable inside of Void function? -
i have function
public func lastactivityfor(username: string) -> string { var lastseeninfo = "date" onelastactivity.sendlastactivityquerytojid((username), sender: onechat.sharedinstance.xmpplastactivity) { (response, forjid, error) -> void in if let timeinseconds = response?.lastactivityseconds() { let time: nsnumber = nsnumber(unsignedlong: timeinseconds) switch timeinseconds { case 0: lastseeninfo = "online" case _ timeinseconds > 0 && timeinseconds < 60: lastseeninfo = "last seen \(timeinseconds) seconds ago" case _ timeinseconds > 59 && timeinseconds < 3600: lastseeninfo = "last seen \(timeinseconds / 60) minutes ago" case _ timeinseconds > 3599 && timeinseconds < 86400: lastseeninfo = "last seen \(timeinseconds / 3600) hours ago" case _ timeinseconds > 86399: let date = nsdate(timeintervalsincenow:-time.doublevalue) let dateformatter = nsdateformatter() dateformatter.dateformat = "dd.mm.yyyy" lastseeninfo = "last seen on \(dateformatter.stringfromdate(date))" default: lastseeninfo = "never been online" } } } return lastseeninfo }
but when it's done, lastseeninfo
variable doesn't change , still equal "date".
when call other file:
print(onelastactivity.sharedinstance.lastactivityfor("username_here"))
it prints
date last seen time ago
so works asynchronously how see. how can fix it? want fix without dispatch_async
. how can modify function without touching nested function , -> void
part?
i think problem request/response async in nature. old value being returned before result has finished.
two solutions: either make variable class instance , mutate it. making void return. or wait block finish risky , ill-advised design point of view
why not have class instance , use didset method? in class (view controller?)
public func lastactivityfor(username: string) { onelastactivity.sendlastactivityquerytojid((username), sender: onechat.sharedinstance.xmpplastactivity) { (response, forjid, error) -> void in if let timeinseconds = response?.lastactivityseconds() { let time: nsnumber = nsnumber(unsignedlong: timeinseconds) switch timeinseconds { case 0: self.lastseeninfo = "online" case _ timeinseconds > 0 && timeinseconds < 60: self.lastseeninfo = "last seen \(timeinseconds) seconds ago" case _ timeinseconds > 59 && timeinseconds < 3600: self.lastseeninfo = "last seen \(timeinseconds / 60) minutes ago" case _ timeinseconds > 3599 && timeinseconds < 86400: self.lastseeninfo = "last seen \(timeinseconds / 3600) hours ago" case _ timeinseconds > 86399: let date = nsdate(timeintervalsincenow:-time.doublevalue) let dateformatter = nsdateformatter() dateformatter.dateformat = "dd.mm.yyyy" self.lastseeninfo = "last seen on \(dateformatter.stringfromdate(date))" default: self.lastseeninfo = "never been online" } } } } var lastseeninfo:nsdate? { didset { //update display or } }
Comments
Post a Comment