繁体   English   中英

iOS-应用程式在背景中时的aSyncAfter

[英]iOS - aSyncAfter while app is in background

我正在尝试运行一个简单的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就不会运行。

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

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

谢谢! :)

做法:

  • 在时间间隔内使用UNNotificationRequest
  • 下面提到的解决方案将在以下情况下工作:
    • 前景
    • 背景
    • 应用已关闭

脚步:

  1. 设置代表(在前台收到警报)
  2. 请求用户授权以发出警报
  3. 创建通知
  4. 将其添加到通知中心

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM