iOS - aSyncAfter应用程序在后台

时间:2017-09-17 23:07:16

标签: ios swift

我正在尝试运行一个简单的iOS应用程序,该应用程序会在指定时间后将通知推送到用户的屏幕。

到目前为止,这就是我所拥有的(借用另一个主题):

DispatchQueue.global(qos: .background).async {
     print( "background task" )

     DispatchQueue.main.asyncAfter( deadline: .now() + milliseconds( 2000 )) {
       let content = UNMutableNotificationContent()
       content.body = "Testing :)"
       content.badge = 1

       let trigger = UNTimeIntervalNotificationTrigger( timeInterval: 2, repeats: false )
       let request = UNNotificationRequest( identifier: "test", content: content, trigger: trigger )

       UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

       print( "background finish" )
     }
}

我唯一的问题是,只要应用程序在后台,aSync After就不会运行。

例如,如果用户进入其锁屏或其他应用,则通知永远不会被触发。

有人会建议我如何实现这个目标吗?

谢谢! :)

1 个答案:

答案 0 :(得分:2)

的方法:

  • 使用UNNotificationRequest时间间隔
  • 下面提到的解决方案适用于以下场景:
    • 前景
    • 背景
    • 应用已关闭

步骤:

  1. 设置委托(在前台提醒)
  2. 请求用户授权以提醒
  3. 创建通知
  4. 将其添加到通知中心
  5. 的AppDelegate:

    AppDelegate必须符合UNUserNotificationCenterDelegate

    将通知中心的代理设置为AppDelegate

    import UserNotifications
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch.
    
            UNUserNotificationCenter.current().delegate = self
    
            return true
        }
    
        //MARK: UNUserNotificationCenterDelegate
    
        //This is required to be alerted when app is in foreground
        func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    willPresent notification: UNNotification,
                                    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            print("will present")
            completionHandler([.alert, .badge, .sound])
        }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    didReceive response: UNNotificationResponse,
                                    withCompletionHandler completionHandler: @escaping () -> Void) {
            print("did receive")
        }
    }
    

    设置通知:

    import UserNotifications
    
    private func setupNotification() {
    
        requestAuthorization { [weak self] isGranted, error in
    
            if let error = error {
    
                print("Request Authorization Error: \(error)")
                return
            }
    
            guard isGranted else {
                print("Authorization Denied")
                return
            }
    
            self?.addNotification()
        }
    }
    
    private func requestAuthorization(completionBlock: @escaping (Bool, Error?) -> ()) {
    
        let center = UNUserNotificationCenter.current()
    
        center.requestAuthorization(options: [.alert, .badge, .sound]) { isGranted, error in
    
            completionBlock(isGranted, error)
        }
    }
    
    
    private func addNotification() {
    
        let content = UNMutableNotificationContent()
    
        content.title = "Testing Notification"
        content.body = "This is a test for notifications"
        content.sound = .default()
    
        let timeInterval = TimeInterval(5)
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
    
        let request = UNNotificationRequest(identifier: "Something",
                                            content: content,
                                            trigger: trigger)
    
    
        let center = UNUserNotificationCenter.current()
    
        center.add(request) { error in
    
            if let error = error {
                print("Error adding notification request: \(error)")
            }
            else {
                print("Successfully added notification request")
            }
        }
    }