2016-07-21 13 views
0

Ich habe einen Push-Benachrichtigungstest erstellt. Ich habe einen Code erstellt, dass, wenn die App in den Hintergrund geht, jede 10 Sekunden die App eine lokale Push-Benachrichtigung anzeigt. Der Code funktioniert in einigen Minuten gut. Nach einigen Minuten hören die Arbeiten im Hintergrund auf. Ich denke, dass iOS nach einiger Zeit die Arbeit, die auf dem Hintergrund läuft, beendet hat. Ist es? Gibt es eine Möglichkeit, dass das iOS meine Arbeit im Hintergrund nicht stoppt?Hintergrundarbeiten an iOS9

Dies ist mein 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:. 
} 


} 
+0

haben Sie Hintergrundmodi aktiviert –

+0

Humm, ich habe nur einen Code erstellt. Wo ich es mache? –

+0

Klicken Sie auf Projekt im Projektnavigator -> Projektziel -> Fähigkeiten -> Scrollen Sie nach unten zu Hintergrundmodi und schalten Sie den Schalter ein. Sie müssen jeden Dienst aktivieren, der für Ihre App am besten geeignet ist, um im Hintergrund ausgeführt zu werden. Weitere Hilfe finden Sie unter http://stackoverflow.com/questions/8943214/iphone-nstimers-in-background?rq=1#comment11195182_8943911 –

Antwort

0

Wenn Sie Ihre App im Hintergrund-Modus ausgeführt halten wollen und töten (beendet) Modus, das Senden von localnotification hält alle 10 Sekunden.

Mit APNS wird Ihre App nicht im Hintergrund aufgerufen. Es wird nur aufgerufen, wenn die Benachrichtigung angeklopft wird und didReceiveLocalNotification aufgerufen wird.

Dann müssen Sie Push-Kit-Bibliothek verwenden. Wenn Push-Kit-Payload mit Silent kommt, wird Ihre App im Hintergrund für 30 Sekunden aufgerufen, selbst wenn sie sich im beendeten Modus befindet.

So können Sie 3 Mal bei jeder 10 Sekunden lokalen Benachrichtigung planen. dann muss man nach 30 Sekunden wieder Push-Kit-Payload erhalten.

0

Danke von hilfe. Ich wurde iOS-Dokumentation gelesen und in der Regel, Apps, die mit konstanter Hintergrund-Modus arbeiten, sind Spieler Musik, Gesundheit zum Beispiel. Andere App wird nach ein paar Minuten getötet, iOS tut es, weil Hintergrund-Anwendungen verbrauchen Batterie und Verarbeitung, so dass nur eine Art von Apps hat die Erlaubnis, auf Hintergrund zu arbeiten Aber ich kann Remote-Benachrichtigung verwenden. Ich werde es versuchen.