【Swift】ローカル通知を実装する

完成図

 

 

 

ストーリーボード

 

 

f:id:nekokichi_yos2:20181022125926p:plain

 

ソースコード

 ViewController

import UIKit
import UserNotifications

class ViewController: UIViewController {
    
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func pushButton(_ sender: Any) {
        
        //プッシュ通知のインスタンス
        let notification = UNMutableNotificationContent()
        //通知のタイトル
        notification.title = textField.text!
        //通知の本文
        notification.body = "これはプッシュ通知です"
        //通知の音
        notification.sound = UNNotificationSound.default
        
        //ナビゲータエリア(ファイルが載っている左)にある画像を指定
        if let path = Bundle.main.path(forResource: "猫", ofType: "png") {
            
            //通知に画像を設定
            notification.attachments = [try! UNNotificationAttachment(identifier: "ID",
                                                url: URL(fileURLWithPath: path), options: nil)]
            
        }
        
        //通知タイミングを指定(今回は5秒ご)
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        //通知のリクエスト
        let request = UNNotificationRequest(identifier: "ID", content: notification,
                                            trigger: trigger)
        //通知を実装
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        
    }
    
}

 

AppDelegate

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


    //プッシュ通知の許可をユーザーに要求する
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions:
                            [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        UNUserNotificationCenter.current().delegate = self
        
        UNUserNotificationCenter.current().requestAuthorization(options:
                                    [.alert,.sound,.badge]) { (granted, error) in
            
        }
        
        return true
    }
    
    //アプリ内(フォアグラウンド)でプッシュ通知を送る
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                        willPresent notification: UNNotification,
                            withCompletionHandler completionHandler:
                                @escaping (UNNotificationPresentationOptions) -> Void) {
        
        completionHandler([.alert,.sound])
        
    }