2

ローカル通知用のパブリック関数があり、その関数を applicationWillTerminate で呼び出したいと考えています。これを試してみると、何も起こりません。viewDidLoadでそれを呼び出すと、正常に機能するため、ローカル通知機能は問題ないと確信しています。


これはローカル通知用の関数です。

func scheduleLocalNotification(second: Double) {

    if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()

        let content = UNMutableNotificationContent()
        content.badge = 1
        content.title = "Title!"
        content.body = "Message!"
        content.categoryIdentifier = "id"
        content.userInfo = ["key": "value"]
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: second, repeats: false)

        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        center.add(request)
    } else {
        // Fallback on earlier versions
    }
}

AppDelegate;

func applicationWillTerminate(_ application: UIApplication) {

        scheduleLocalNotification(second: 30.0)
        print("Terminating!")

        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

SOで同様の問題を検索したところ、2つの質問が見つかりましたが、どれも私の問題を解決しません。

アプリSwift 2の終了後にローカル通知を送信する

アプリケーション終了時のローカル通知


編集:承認をリクエストします。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
        if (!launchedBefore)  {
            if #available(iOS 10.0, *) {
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                    if granted {
                        print("Authorization granted!")
                    } else {
                        print("Authorization not granted!")
                    }
                }
            } else {
                let settings = UIUserNotificationSettings(types: [.alert, .badge , .sound], categories: nil)
                UIApplication.shared.registerUserNotificationSettings(settings)
            }

            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }

        // Override point for customization after application launch.
        return true
    }
4

2 に答える 2