当 App 在后台 运行 时发送本地通知 Swift 2.0

Send Local Notifications while App is running in the background Swift 2.0

我正在尝试在用户最小化应用程序时向用户发送 'Push Notification style' 提醒(通过单击 iPhone 的主页按钮或同时锁定 phone ).

我的应用程序连续解析一个 XML 文件(每 10 秒),我希望该应用程序继续 运行 以便在我的应用程序满足某些条件后向用户发送本地通知程序,即使在用户最小化应用程序或锁定他们的 phone.

之后

我已经从教程中恢复过来,每个人似乎都'schedule' 通知,但这对我不起作用,因为我的通知不是基于时间的,而是基于条件的遇见了

到目前为止我做了什么:

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

当应用程序打开时,警报效果很好,但当我在 phone 上最小化应用程序时,通知从未出现。我假设该应用程序在后台时不是 运行,或者我不太了解这个概念。非常感谢任何帮助。

默认情况下,NSTimer 只在模拟器中工作。尝试将此添加到您的 AppDelegate 文件中:

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
    }