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

Iva*_*van 6 nstimer ios uilocalnotification swift 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
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

应用程序打开时,警报工作正常,但是当我最小化手机上的应用程序时,通知永远不会显示.我假设应用程序在后台运行时没有运行,或者我不太了解这个概念.任何帮助是极大的赞赏.

小智 9

默认情况下,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
    }
Run Code Online (Sandbox Code Playgroud)

  • @Nadia 经过无数小时的搜索和教程后,“beingbackgroundtaskwithname”起作用了。谢谢你的回答 (2认同)