簡體   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