我正在开发一个应用程序,我想让用户知道它是在后台模式下通过其中一个横幅打开,就像你使用Uber或Alarm Cycle时一样。 我知道如果你使用位置它会添加它但我不想这样做(可能会被拒绝)。
有没有办法添加这个横幅?
答案 0 :(得分:0)
<强> 1。打开AppDelegate.swift文件
<强> 2。在iOS上注册您的应用程序,以便能够在applicationDidFinishLaunchingWithOptions中发送用户通知
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerForNotifications()
return true
}
func registerForNotifications() {
// Register for notification: This will prompt for the user's consent to receive notifications from this app.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
}
}
第3。填写您希望通知关闭的内容和时间,并将其另存为UNNotificationRequest。 (我在添加通知后一秒钟就离开了。)
func createBackgroundNotificationRequest() -> UNNotificationRequest {
let content = UNMutableNotificationContent()
content.title = "Entered Background Mode"
content.subtitle = "Just so you are aware."
content.body = "We'll be waiting for you back in the app"
let request = UNNotificationRequest(identifier: "BackgroundNotification", content: content, trigger: UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false))
return request
}
<强> 4。将请求添加到applicationDidEnterBackground状态内的UNUserNotificationCenter.current()
func applicationDidEnterBackground(_ application: UIApplication) {
let notificationRequest = createBackgroundNotificationRequest()
UNUserNotificationCenter.current().add(notificationRequest, withCompletionHandler: nil)
}
Here's a demo project I made performing the task you want.
只需打开应用,授权通知,然后点击主页按钮,即可触发后台通知。