ios - 应用程序在后台运行时发送本地通知 Swift 2.0

标签 ios swift nstimer uilocalnotification uialertaction

我试图在用户最小化应用程序时(通过单击 iPhone 的主页按钮或同时锁定手机)向用户发送“推送通知样式”警报。

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

我已经从教程中恢复过来,每个人似乎都在“安排”通知,但这对我不起作用,因为我的通知不是基于时间的,而是基于满足的条件。

到目前为止我做了什么:

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

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

最佳答案

默认情况下,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
    }

关于ios - 应用程序在后台运行时发送本地通知 Swift 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35008731/

相关文章:

ios - 在 iphone 中按下耳机按钮时的延迟

iOS可用架构问题

swift - 测试内存中 Realm 迁移

ios - Swift:如何使用 Sprite 套件游戏实现额外的 View Controller ?

Swift 3 更新表示调用函数之间的时间间隔的变量

iOS - 在 Swift 中使用 NSJSONSerialization 解析 JSON 字典

ios - Xcode 6 的最低 iOS 部署目标

ios - 无法在桥接文件中导入 "fscalendar.h"

ios - 带有 NSTimer 的单例不从 AppDelegate 触发

objective-c - Xcode - NSTimer 以随机间隔触发?没有一致性