Alamofire在后台应用时请求

时间:2015-11-19 21:30:32

标签: ios json swift background alamofire

您好我想使用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")
                        }
                    }
                }
            }
    }
}

由于

1 个答案:

答案 0 :(得分:0)

我认为@Paulw11在他的评论中回答了你的问题,你不能在后台使用NSTimer,Apple有一个已知的可在后台制作的任务列表,你可以阅读更多{{ 3}}。

但是,让我们考虑一下您尝试实现的目标,让我们假设您可以使用NSTimer进行操作,然后您的应用程序在后台消耗内存和设备中的电池不断尝试从您的服务器获取更新,根本不建议这样做。

为此,Apple / Google推出了Apple推送通知(Google:Android推送通知),以处理服务器在后台处于通知状态时通知应用程序服务器,让我们说一个新邮件,一个消息应用程序的新消息等等。

然后,您拥有的选项是使用Apple提出的服务,您可以在以下文档中阅读更多内容:

我希望这对你有所帮助。