我有一个功能
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 _ where timeInSeconds > 0 && timeInSeconds < 60:
lastSeenInfo = "last seen \(timeInSeconds) seconds ago"
case _ where timeInSeconds > 59 && timeInSeconds < 3600:
lastSeenInfo = "last seen \(timeInSeconds / 60) minutes ago"
case _ where timeInSeconds > 3599 && timeInSeconds < 86400:
lastSeenInfo = "last seen \(timeInSeconds / 3600) hours ago"
case _ where 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
}
但是当它完成后,我的lastSeenInfo
变量不会发生变化,仍然等于&#34; date&#34;。
当我从其他文件中调用它时:
print(OneLastActivity.sharedInstance.lastActivityFor("username_here"))
打印
date
last seen some time ago
所以我看到的是异步工作。我该如何解决?但我想在没有dispatch_async
的情况下解决它。如何在不触及嵌套函数和-> Void
部分?
答案 0 :(得分:1)
我认为问题是请求/响应本质上是异步的。在结果完成之前返回旧值。
两种解决方案: 将变量设为类实例并对其进行变异。让它无效回归。 要么 等待块完成,但从设计的角度来看这是冒险和不明智的
为什么没有类实例并使用didSet方法? 在你的班级(查看控制器?)
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 _ where timeInSeconds > 0 && timeInSeconds < 60:
self.lastSeenInfo = "last seen \(timeInSeconds) seconds ago"
case _ where timeInSeconds > 59 && timeInSeconds < 3600:
self.lastSeenInfo = "last seen \(timeInSeconds / 60) minutes ago"
case _ where timeInSeconds > 3599 && timeInSeconds < 86400:
self.lastSeenInfo = "last seen \(timeInSeconds / 3600) hours ago"
case _ where 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 something
}
}