AppDelegate
에서 이전에 앱을 열 었는지 여부를 저장해야합니다.
AppDelegate에
//make sure to import the framework
//additionally, if you want to customize the notification's UI,
//import the UserNotificationsUI
import UserNotifications
//default value is true, because it will be set false if this is not the first launch
var firstLaunch: Bool = true
let defaults = UserDefaults.standard
//also make sure to include *UNUserNotificationCenterDelegate*
//in your class declaration of the AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
//get whether this is the very first launch
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let bool = defaults.object(forKey: "firstLaunch") as? Bool {
firstLaunch = bool
}
defaults.set(false, forKey: "firstLaunch")
defaults.synchronize()
//ask the user to allow notifications
//maybe do this some other place, where it is more appropriate
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in}
return true
}
//schedule your notification when exiting the app, if necessary
func applicationDidEnterBackground(_ application: UIApplication) {
//update the variable
if let bool = defaults.object(forKey: "firstLaunch") as? Bool {
firstLaunch = bool
}
if !firstLaunch {
//abort mission if it's not the first launch
return
}
//customize your notification's content
let content = UNMutableNotificationContent()
content.title = "Survey?"
content.body = "Would you like to take a quick survey?"
content.sound = UNNotificationSound.default()
//schedule the notification
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "takeSurvey", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)
}
에서 마지막으로, 당신이받은 응답을 처리하고 링크를 엽니 다. 그게 다야!
"didFinishLaunching"에서 firstLaunch = false로 설정하면 ... "didEnterBackground()"에서 어떻게 사실 일 수 있습니까? 또는 나는 무엇인가 놓치고 있냐? – OliverM
사실이에요. 그래도 내 코드를 사용해 보셨나요? 나를 위해 그것은 자동적으로 작동합니다. 그렇지 않다면, 통지가 예정되어 있거나'firstLaunch'가 읽혀진 직후에 그 두 줄을'applicationDidEnterBackground()'로 옮길 수 있습니다. 그게 어떻게되는지 알려줘! – LinusGeffarth