【发布时间】:2015-11-19 21:30:32
【问题描述】:
您好,我想使用 Alamofire 和 NSTimer 获取一些数据
应用程序在前台运行良好,计时器设置为每 30 秒调用一次 GetEstado 函数,但是当应用程序进入后台时计时器暂停,如果我的服务器更新了某些内容,它实际上并没有在应用程序上更新
这是我的代码
func GetEstado(){
Alamofire.request(.POST, "https://myurl/getestado.php", parameters: ["id": id])
.responseString { rta in
if let dataFromString = rta.result.value!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
for (key,subJson):(String, JSON) in json {
if(key=="e"){
if(subJson.stringValue=="1"){
self.Timer.invalidate()
print("ACTUALIZACION")
let notification = UILocalNotification()
notification.fireDate = NSDate(timeIntervalSinceNow: 5)
notification.alertBody = "UPDATED"
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
self.performSegueWithIdentifier("UPDATED", sender: self)
}
else{
print("UPS")
}
}
}
}
}
}
谢谢
【问题讨论】:
-
您的应用在后台时不能使用 NSTimer,因为执行已暂停。您可以使用后台获取,但这最多只会每隔几个小时执行一次。您还可以使用来自服务器的推送消息。以你现在的方式轮询在带宽和电池电量方面非常低效。
标签: ios json swift background alamofire