LoginSignup
5
7

More than 5 years have passed since last update.

Swift ローカル通知

Last updated at Posted at 2018-07-29

ローカル通知を設定 

viewController.swift
import UserNotification

//通知のタイトルと内容を設定
let content = UNMutableNotificationContent()
content.title = "(タイトル)"
content.body = "(内容)"
content.sound = UNNotificationSound.default() //通知音

//通知する日付を設定
let date:Date = (通知したい日付)
let calendar = Calendar.current()
let dateComponent = calendar.dateComponents([.year, .month, .day, .hour, minute] , from: date)

//以上の通知をリクエストに指定
let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponent, repeats: false)
let request = UNNotificationRequest.init(identifier: "一意の値", content: content,//UNMutableNotificationContent trigger: trigger //UNNotificationTrigger)

//通知を設定
let center = UNNotificationCenter.current()
center.add(request, completion: nil)

ユーザーへローカル通知の許諾の通知

AppDelegate.swift
import UserNotification

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert,.sound]){(granted, error) in

        }

        center.delegate = self;
        return true
    }

またアプリ起動中でもローカル通知を表示させるためのコード

AppDelegate.swift
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.sound, .alert])
    }
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7