简体   繁体   中英

Alamofire request when app in background

Hi I want to fetch some data using Alamofire and a NSTimer

The app works fine on foreground, the timer is set to call the GetEstado function each 30 seconds but when the app enters background the timer is paused and if my server updates something it does not actually updates on the app

Here's my code

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")
                        }
                    }
                }
            }
    }
}

Thanks

I think @Paulw11 answer your question in his comment, you can't use NSTimer in background, Apple has a known list of the task that can be produced in background, you can read more here .

But let think for a moment what you're trying to achieve, let suppose you can do it using NSTimer , then you have your app in background consuming memory and battery in your device constantly to try to get the updates from your server, this is not recommended at all.

It's for this that Apple/Google introduced Apple Push Notifications (Google: Android Push Notifications) to handle that the server notifies the app when it's in background or inactive regarding any task that is programmed in the server, lets say a new mail, a new message in the case of messaging apps, etc.

Then, the option you have is use the service proposed by Apple, you can read more in the following docs:

I hope this help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM