ただいまswiftのローカルプッシュ通知を学んでおり、その中でTimerを使う機会がありました。
参加書などを参考にし、なんとか下のプログラムを完成させることができ、ビルドも成功しました。
swift
1 2import UIKit 3import UserNotifications 4 5class ViewController2: UIViewController { 6 7 @IBOutlet var nameTextField: UITextField! 8 9 10 @IBOutlet var textField1: UITextField! 11 12 @IBOutlet var textField2: UITextField! 13 14 @IBOutlet var textField3: UITextField! 15 16 @IBOutlet var textField4: UITextField! 17 18 var timer:Timer? 19 20 override func viewDidLoad() { 21 super.viewDidLoad() 22 23 // Do any additional setup after loading the view. 24 } 25 26 27 @IBAction func push(_ sender: Any) { 28 29 timerUpdate() 30 31 } 32 33 34 func timerUpdate(){ 35 36 let content = UNMutableNotificationContent() 37 let content2 = UNMutableNotificationContent() 38 let content3 = UNMutableNotificationContent() 39 let content4 = UNMutableNotificationContent() 40 41 content.title = nameTextField.text! 42 content.sound = UNNotificationSound.default 43 content.body = textField1.text! 44 45 let trigger1 = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) 46 47 let request1 = UNNotificationRequest(identifier: "ID2", content: content, trigger: trigger1) 48 UNUserNotificationCenter.current().add(request1,withCompletionHandler: nil) 49 50 51 content2.title = nameTextField.text! 52 content2.body = textField2.text! 53 let trigger2 = UNTimeIntervalNotificationTrigger(timeInterval: 8, repeats: false) 54 let request2 = UNNotificationRequest(identifier: "ID3", content: content2, trigger: trigger2) 55 UNUserNotificationCenter.current().add(request2,withCompletionHandler: nil) 56 57 content3.title = nameTextField.text! 58 content3.body = textField3.text! 59 let trigger3 = UNTimeIntervalNotificationTrigger(timeInterval: 11, repeats: false) 60 let request3 = UNNotificationRequest(identifier: "ID4", content: content3, trigger: trigger3) 61 UNUserNotificationCenter.current().add(request3,withCompletionHandler: nil) 62 63 content4.title = nameTextField.text! 64 content4.body = textField4.text! 65 66 if let path = Bundle.main.path(forResource: "bird", ofType: "jpg"){ 67 68 content4.attachments = [try! UNNotificationAttachment(identifier: "ID5", url: URL(fileURLWithPath:path ), options: nil)] 69 70 } 71 72 let trigger4 = UNTimeIntervalNotificationTrigger(timeInterval: 14, repeats: false) 73 let request4 = UNNotificationRequest(identifier: "ID5", content: content4, trigger: trigger4) 74 UNUserNotificationCenter.current().add(request4,withCompletionHandler:nil) 75 76} 77
しかしこの中で何故Timerが必要なのか?また必要であれば今まで自分はvar 変数名 = Timer()と変数に代入して使うやり方、もしくはTimer.scheduledTimer()のようなものを個別に使うことしか経験がなく、なぜvar timer:Timer?という形になったのかが理解できませんでした。
もしわかる方がいましたら、是非教えていただきたいです。よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/25 18:15