【问题标题】:Alamofire request when app in background应用程序在后台时的 Alamofire 请求
【发布时间】:2015-11-19 21:30:32
【问题描述】:

您好,我想使用 Alamofire 和 NSTimer 获取一些数据

应用程序在前台运行良好,计时器设置为每 30 秒调用一次 GetEstado 函数,但是当应用程序进入后台时计时器暂停,如果我的服务器更新了某些内容,它实际上并没有在应用程序上更新

p>

这是我的代码

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


【解决方案1】:

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

但是让我们想一想您想要实现的目标,假设您可以使用 NSTimer 来实现它,然后您的应用程序在后台会不断消耗设备中的内存和电池以尝试从中获取更新您的服务器,完全不建议这样做。

为此,Apple/Google 引入了 Apple Push Notifications(Google:Android Push Notifications)来处理服务器在后台或不活动时通知应用程序关于服务器中编程的任何任务的问题,比如说一封新邮件, 消息应用等情况下的新消息。

那么,您可以选择使用 Apple 提出的服务,您可以在以下文档中阅读更多内容:

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多