gpt4 book ai didi

iOS - 当应用程序处于后台时的 aSyncAfter

转载 作者:搜寻专家 更新时间:2023-11-01 07:08:46 26 4
gpt4 key购买 nike

我正在尝试运行一个简单的 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. 设置委托(delegate)(在前台提醒)
  2. 请求用户授权以提醒
  3. 创建通知
  4. 将其添加到通知中心

应用委托(delegate):

AppDelegate 必须符合 UNUserNotificationCenterDelegate

将通知中心的委托(delegate)设置为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")
}
}
}

关于iOS - 当应用程序处于后台时的 aSyncAfter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com