獣は月夜に何を見る...

【 iPhone 】Swiftでアプリ開発 | UserNotifications

ローカル通知の覚書

iOSにおいて、アプリが起動していなくても、スケジュール等を通知してくれるアレ。

Main.storyboardにNavigation Controllerを追加。


f:id:tukumosanzou:20180803014128j:plain

ViewController.swift

import UIKit
import UserNotifications

//受信通知と通知関連の操作を処理するためのインタフェース。UNUserNotificationCenterのdelegateプロパティを使うのに必要。
class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        //ナビゲーションバーの左ボタンを追加する。
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Register", style: .plain, target: self, action: #selector(registerLocal))

        //ナビゲーションバーの右ボタンを追加する。
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Schedule", style: .plain, target: self, action: #selector(scheduleLocal))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc func registerLocal() {

        //通知センターの取得、アプリまたはアプリ拡張の共有ユーザー通知センターオブジェクトを返します。
        let center = UNUserNotificationCenter.current()

        //ユーザーのデバイスにローカルおよびリモートの通知が配信されたときに、ユーザーと対話するための認可を要求します。
        //options: UNAuthorizationOptions = []
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("Yay!")
            } else {
                print("D'oh")
            }
            
        }
    }
    
    @objc func scheduleLocal() {
        registerCategories()
        
        let center = UNUserNotificationCenter.current()

        //すべての保留中の通知要求のスケジュールを解除します。
        center.removeAllPendingNotificationRequests()

        //通知の編集可能なコンテンツ。
        let content = UNMutableNotificationContent()

        //通知アラートに表示するためのローカライズされた文字列を返します。
        content.title = NSString.localizedUserNotificationString(forKey: "Late wake up call", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "The early bird catches the worn, but the second mouse gets chees.", arguments: nil)

        //通知のタイプを表すカテゴリオブジェクトの識別子。
        content.categoryIdentifier = "alarm"

        //通知に関連付けられたカスタム情報の辞書。
        content.userInfo = ["customData": "fizzbuzz"]

        //通知が配信されたときに再生されるサウンド。
        content.sound = UNNotificationSound.default()

        //このオブジェクトの作成に使用された日付コンポーネント。
        var dateComponents = DateComponents()
        dateComponents.hour = 10
        dateComponents.minute = 30

        //指定された時間が経過した後に通知を配信するトリガー条件。
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

        //特定の日時に通知を配信するトリガー条件。
//        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

        //ローカル通知をスケジュールする要求。通知の内容と配信のトリガー条件が含まれます。
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        center.add(request)
    }
    
    //func scheduleLocal()内部で最初に呼び込む。
    func registerCategories() {
        let center = UNUserNotificationCenter.current()

        //受信通知と通知関連の処理を処理するオブジェクト、UNUserNotificationCenterDelegateを継承する必要がある。
        center.delegate = self

        //配信された通知に応答して実行するタスク。
        let show = UNNotificationAction(identifier: "show", title: "Tell me more ", options: .foreground)

        //あなたのアプリがサポートしている通知のタイプとそれを使って表示するカスタムアクション。
        let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: [])

        //アプリケーションの通知タイプと、それがサポートするカスタムアクションを登録します。
        center.setNotificationCategories([category])
    }
    //デリゲートに、配信された通知に対するユーザーの応答を処理するように要求します。
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        
        if let customData = userInfo["customData"] as? String {
            print("Custom data received: \(customData)")

            //ユーザーが選択したアクションの識別子文字列。
            switch response.actionIdentifier {

            //ユーザーが通知インターフェイスを右にスライドさせてからアプリを開いたことを示すアクション
            case UNNotificationDefaultActionIdentifier:
                
                print("Default identifier")
              
            //ユーザーが通知インターフェイスを左にスライドさせてからアプリを開いたことを示すアクション
            //UNUserNotificationActionのidentifierプロパティの値
            case "show":
                
                print("Show more information...")
                
            default:
                break
            }
        }

        //終了時には、必ず補完ハンドラを呼び出します。
        //ユーザーの応答を処理した後、このブロックを実行して、完了したことをシステムに知らせる必要があります。
        completionHandler()
    }
}




UNUserNotificationCenter | Apple Developer Documentation

 func registerCategories() {
        let center = UNUserNotificationCenter.current()

        //受信通知と通知関連の処理を処理するオブジェクト、UNUserNotificationCenterDelegateを継承する必要がある。
        center.delegate = self

delegate = self とするためにはUNUserNtificationCenterDelegateをclassに追加する必要がある。

import UIKit
import UserNotifications

//受信通知と通知関連の操作を処理するためのインタフェース。UNUserNotificationCenterのdelegateプロパティを使うのに必要。
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
 //ユーザーが通知インターフェイスを右にスライドさせてからアプリを開いたことを示すアクション
            case UNNotificationDefaultActionIdentifier:
                
                print("Default identifier")
              
            //ユーザーが通知インターフェイスを左にスライドさせてからアプリを開いたことを示すアクション
            //UNUserNotificationActionのidentifierプロパティの値
            case "show":
                
                print("Show more information...")



右スライドでOpenをクリック。 f:id:tukumosanzou:20180803021934j:plain コマンドパレットには以下のように表示される。 f:id:tukumosanzou:20180803024252j:plain



左スライドでViewをクリック。 f:id:tukumosanzou:20180803022005j:plain 表示がこうなるので、「Tell me more」をクリック。 f:id:tukumosanzou:20180803025056j:plain コマンドパレットには以下のように表示される。 f:id:tukumosanzou:20180803025125j:plain




@objc func registerLocal() {

        //通知センターの取得、アプリまたはアプリ拡張の共有ユーザー通知センターオブジェクトを返します。
        let center = UNUserNotificationCenter.current()

        //ユーザーのデバイスにローカルおよびリモートの通知が配信されたときに、ユーザーと対話するための認可を要求します。
        //options: UNAuthorizationOptions = []
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("Yay!")
            } else {
                print("D'oh")
            }
            
        }
    }

UNUserNotificationCenter | Apple Developer Documentation

あなたのアプリやアプリの拡張子のすべての通知関連行動を管理するために共有UNUserNotificationCenterオブジェクトを使用します。

requestAuthorization(options:completionHandler:) | Apple Developer Documentation

Parameters options --- UNAuthorizationOptionsを継承。 completionHandler granted error ローカルおよびリモートの通知がユーザーのデバイスに配信されたときに、ユーザーと対話するための承認を要求します。




//func scheduleLocal()内部で最初に呼び込む。
    func registerCategories() {
        let center = UNUserNotificationCenter.current()

        //受信通知と通知関連の処理を処理するオブジェクト、UNUserNotificationCenterDelegateを継承する必要がある。
        center.delegate = self

        //配信された通知に応答して実行するタスク。
        let show = UNNotificationAction(identifier: "show", title: "Tell me more ", options: .foreground)

        //あなたのアプリがサポートしている通知のタイプとそれを使って表示するカスタムアクション。
        let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: [])

        //アプリケーションの通知タイプと、それがサポートするカスタムアクションを登録します。
        center.setNotificationCategories([category])
    }

UNNotificationAction | Apple Develper Documentation

UNNotificationActionオブジェクトを使用して、配信された通知に応じてアプリケーションが実行できるアクションを定義します。

あなたのアプリがサポートするアクションを定義します。

たとえば、ミーティングのアプリケーションは、ミーティングの招待を受け入れるか拒否するかのアクションを定義します。

アクションオブジェクト自体には、アクションボタンとボタンの外観に表示するタイトルが含まれています。

アクションオブジェクトを作成したら、それらをUNNotificationCategoryオブジェクトに追加し、カテゴリーをシステムに登録します。

UNNotificationActionOptions | Apple Developer Documentation

.foreground --- このアクションにより、アプリはフォアグラウンドで起動します。

ユーザーがこのオプションを含むアクションを選択すると、システムはアプリケーションをフォアグラウンドに持ち込み、ユーザーに必要に応じてデバイスのロックを解除するように要求します。

このオプションは、ユーザーがあなたのアプリをさらに操作する必要がある操作に使用します。

単にこのオプションを使用してアプリケーションをフォアグラウンドに持ってこないでください。