Guest User

Untitled

a guest
Nov 22nd, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. //
  2. // ViewController.swift
  3. // NotificationCenter
  4. //
  5. // Created by strawb3rryx7 on 21.11.2017.
  6. // Copyright © 2017 strawb3rryx7. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. // Eklediğimiz observer için ortak bir key belirlemeliyiz ki gönderdiğimiz veriyi alabilelim. Global olarak tanımladım ki tekrar tekrar yazmakla uğraşmayalım.
  12. let sendNameNotificationKey = NSNotification.Name(rawValue: "sendNameNotificationKey")
  13.  
  14. class ViewController: UIViewController {
  15. @IBOutlet weak var nameTextField: UITextField!
  16.  
  17. override func viewDidLoad() {
  18. super.viewDidLoad()
  19.  
  20. // Notification göndermek için observerimizi ekliyoruz.
  21. NotificationCenter.default.addObserver(self, selector: #selector(onSendNotification(notification:)), name: sendNameNotificationKey, object: nil)
  22. }
  23.  
  24. // Butonun touchUpInside yani üzerine tıklandığında tetikleyeceği method
  25. @IBAction func onSendButtonTapped(_ sender: UIButton) {
  26. // TextField içerisne yazdığımız metni alıyoruz.
  27. guard let name = nameTextField.text else {
  28. return
  29. }
  30.  
  31. // NotificationCenter.default.post ile Notification'u postluyoruz yani gönderiyoruz.
  32. // userInfo dediğimiz alan [AnyHashable : Any] bir yapıya sahiptir, istediğimiz kullanıcı verisini buradan gönderebiliriz. Receive (alacağımız) edeceğimiz alanda da bu bilgileri kullanabiliriz.
  33. NotificationCenter.default.post(name: sendNameNotificationKey, object: self, userInfo: ["name": name])
  34. }
  35.  
  36. // Observeri eklerken tanımladığımız selector bu alanda gönderilen notification'a erişebilir aynı zamanda observer'in (tetiklendiğinden emin olabiliriz).
  37. @objc func onSendNotification(notification: Notification) {
  38. print("Notification sended.")
  39. }
  40.  
  41. override func didReceiveMemoryWarning() {
  42. super.didReceiveMemoryWarning()
  43. // Dispose of any resources that can be recreated.
  44. }
  45.  
  46.  
  47. }
Add Comment
Please, Sign In to add comment