0

I created a push notification test. I created a code that when app go to background, each 10 second the app show a local push notification. The code works well in some minutes. After some minutes the work on background stop. I think that iOS killed the work that run on background after some time. Is it? There is a way that the iOS dont stop my work on background?

This is my code: ViewController:

import UIKit

class ViewController: UIViewController {

var timer = NSTimer()
 var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    notificatioAppGoToBackground()

    setupNotificationSettings()

    //call handle notifications
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.handleModifyListNotification), name: "modifyListNotification", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.handleDeleteListNotification), name: "deleteListNotification", object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.handleStopTimerNotification), name: "stopTimer", object: nil)


    backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
        UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier!)
    })


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func alert(title:String, message:String ){

    let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
    self.presentViewController(alert, animated: true){}
}

func handleStopTimerNotification(){
    timer.invalidate()
    print("acao foreground")
    UIApplication.sharedApplication().cancelAllLocalNotifications() //cancela a notificacao

}

func handleModifyListNotification() {
    timer.invalidate()
    print("acao editar")
    //alert("Atenção", message: "Modificação ativada, notificação cancelada")
    UIApplication.sharedApplication().cancelAllLocalNotifications() //cancela a notificacao

}

func handleDeleteListNotification() {
    print("executou a exclusao")
}

func setupNotificationSettings() {

    let notificationSettings: UIUserNotificationSettings! = UIApplication.sharedApplication().currentUserNotificationSettings()

    if (notificationSettings.types == UIUserNotificationType.None){

        let notificationTypes: UIUserNotificationType = [.Alert, .Sound, .Badge]

        let modifyListAction = UIMutableUserNotificationAction()
        modifyListAction.identifier = "editList"
        modifyListAction.title = "Edit list"
        modifyListAction.activationMode = UIUserNotificationActivationMode.Foreground
        modifyListAction.destructive = false
        modifyListAction.authenticationRequired = true

        let trashAction = UIMutableUserNotificationAction()
        trashAction.identifier = "trashAction"
        trashAction.title = "Delete list"
        trashAction.activationMode = UIUserNotificationActivationMode.Background
        trashAction.destructive = true
        trashAction.authenticationRequired = true

        let actionsArray = NSArray(objects: modifyListAction, trashAction)
        let actionsArrayMinimal = NSArray(objects: trashAction, modifyListAction)

        // Specify the category related to the above actions.
        let shoppingListReminderCategory = UIMutableUserNotificationCategory()
        shoppingListReminderCategory.identifier = "shoppingListReminderCategory"
        shoppingListReminderCategory.setActions(actionsArray as? [UIUserNotificationAction], forContext: UIUserNotificationActionContext.Default)
        shoppingListReminderCategory.setActions(actionsArrayMinimal as? [UIUserNotificationAction], forContext: UIUserNotificationActionContext.Minimal)


        let categoriesForSettings = NSSet(objects: shoppingListReminderCategory)


        // Register the notification settings.
        let newNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: categoriesForSettings as? Set<UIUserNotificationCategory>)
        UIApplication.sharedApplication().registerUserNotificationSettings(newNotificationSettings)
    }

}

func setActions(actions: [AnyObject]!, forContext context: UIUserNotificationActionContext){}


func notificatioAppGoToBackground(){
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplicationWillResignActiveNotification, object: nil)
}


func appMovedToBackground() {
    print("App moved to background!!!")
    listenerSchedule()
}

func listenerSchedule() {
    timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(ViewController.startNotication), userInfo: nil, repeats: true)
}

func startNotication(){
    let date = NSDate()
    let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([.Day, .Month, .Year, .Hour, .Minute, .Second], fromDate: date)

    if(dateComponets.second < 20){
        print("nao notifica  \(dateComponets.second)" )
    }else{
        print("aguardando notificação  \(dateComponets.second)" )
        let localNotification = UILocalNotification()

        localNotification.alertBody = "Teste de notificação"
        localNotification.alertAction = "View List"
        localNotification.category = "shoppingListReminderCategory"
        localNotification.applicationIconBadgeNumber = dateComponets.second
        localNotification.soundName = UILocalNotificationDefaultSoundName


        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    }


}


}

AppDelegate:

import UIKit

  @UIApplicationMain
  class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {

    print(notificationSettings.types.rawValue)
}

//executa a noficacao agendada com a app aberta
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    // Do something serious in a real app.
    print("Received Local Notification:")
    print(notification.alertBody!)
    application.applicationIconBadgeNumber = 0 //limpa o badge ao carregar a app
    application.cancelAllLocalNotifications() //limpa o badge ao carregar a app
    NSNotificationCenter.defaultCenter().postNotificationName("stopTimer", object: nil)
}
//Essa funcao exibe a notificacao quando a app esta parada ou em segundo plano
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {

    if identifier == "editList" {
        NSNotificationCenter.defaultCenter().postNotificationName("modifyListNotification", object: nil)
    }
    else if identifier == "trashAction" {
        NSNotificationCenter.defaultCenter().postNotificationName("deleteListNotification", object: nil)
    }

    completionHandler()
}




func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    NSNotificationCenter.defaultCenter().postNotificationName("stopTimer", object: nil)
    application.applicationIconBadgeNumber = 0 //limpa o badge ao carregar a app
    application.cancelAllLocalNotifications() //limpa o badge ao carregar a app
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


 }
Sunil Sharma
  • 2,653
  • 1
  • 25
  • 36
  • have you enabled Background Modes – Sunil Sharma Jul 21 '16 at 13:29
  • Humm, I only created a code. Where I do it? – Alexandre C. do Carmo Jul 21 '16 at 17:05
  • Click on project in Project Navigator -> project target -> Capabilities -> Scroll down to Background Modes and turn the switch on. You have to enable any service that suits best for your app to run in background. For more help check this link http://stackoverflow.com/questions/8943214/iphone-nstimers-in-background?rq=1#comment11195182_8943911 – Sunil Sharma Jul 21 '16 at 17:20

2 Answers2

0

If you want to keep your app running in background mode and kill ( terminated ) mode, that keeps sending localnotification at every 10 seconds.

With APNS your app will not get invoke in background. it will only invoke when notification is getting tapped and didReceiveLocalNotification get called.

Then you have to use push kit library. when push kit payload comes with silent it will invoke your app in background for 30 seconds even it is in terminated mode.

So you can schedule 3 times at each 10 seconds local notification. then after 30 seconds again you have to receive push kit payload.

Hasya
  • 9,792
  • 4
  • 31
  • 46
0

Thanks by help. I was read iOS documentation and normally, apps that work using constant background mode are players musics, health for example. Others app is killed after few minutes, iOS do it because background applications consume battery and processing, so only some kind of apps has permission to work on background But I can use remote notification. I gonna try it.