Send local notifications while the app is running in the background Swift 2.0

I am trying to send the user a "Push Notification style" warning when the user minimizes the application (by clicking the "Home iPhone" button or by locking the phone).

My application continuously parses an XML file (every 10 seconds), and I want the application to continue to work so that it sends a local notification to the user when some condition has been met in my program, even after the user minimized the application or blocked his telephone.

I jumped away from the textbooks and everyone seemed to β€œpaint” the notice, but this will not work for me, because my notification is not based on time, rather, it is based on compliance with the conditions.

What i have done so far:

AppDelegate.swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)) return true } 

MapViewController.swift

 // Some function func someFunction(delta: Int) { if delta < 100 { // Send alert to user if app is open let alertView = UIAlertController(title: "This is an Alert!", message: "", preferredStyle: UIAlertControllerStyle.Alert) alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertView, animated: true, completion: nil) // Send user a local notification if they have the app running in the bg pushTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("pushNotification"), userInfo: nil, repeats: false) } } // Send user a local notification if they have the app running in the bg func pushNotification() { let notification = UILocalNotification() notification.alertAction = "Go back to App" notification.alertBody = "This is a Notification!" notification.fireDate = NSDate(timeIntervalSinceNow: 1) UIApplication.sharedApplication().scheduleLocalNotification(notification) } 

Alert works great while the application is open, but the notification never appears when I minimize the application on my phone. I assume that the application does not work while it is in the background, or I do not understand this concept. Any help is appreciated.

+5
source share
1 answer

By default, NSTimer only works in the simulator. Try adding this to your AppDelegate file:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)) application.beginBackgroundTaskWithName("showNotification", expirationHandler: nil) return true } 
+9
source

Source: https://habr.com/ru/post/1241464/


All Articles