Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.swift
- // NotificationCenter
- //
- // Created by strawb3rryx7 on 21.11.2017.
- // Copyright © 2017 strawb3rryx7. All rights reserved.
- //
- import UIKit
- // 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.
- let sendNameNotificationKey = NSNotification.Name(rawValue: "sendNameNotificationKey")
- class ViewController: UIViewController {
- @IBOutlet weak var nameTextField: UITextField!
- override func viewDidLoad() {
- super.viewDidLoad()
- // Notification göndermek için observerimizi ekliyoruz.
- NotificationCenter.default.addObserver(self, selector: #selector(onSendNotification(notification:)), name: sendNameNotificationKey, object: nil)
- }
- // Butonun touchUpInside yani üzerine tıklandığında tetikleyeceği method
- @IBAction func onSendButtonTapped(_ sender: UIButton) {
- // TextField içerisne yazdığımız metni alıyoruz.
- guard let name = nameTextField.text else {
- return
- }
- // NotificationCenter.default.post ile Notification'u postluyoruz yani gönderiyoruz.
- // 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.
- NotificationCenter.default.post(name: sendNameNotificationKey, object: self, userInfo: ["name": name])
- }
- // Observeri eklerken tanımladığımız selector bu alanda gönderilen notification'a erişebilir aynı zamanda observer'in (tetiklendiğinden emin olabiliriz).
- @objc func onSendNotification(notification: Notification) {
- print("Notification sended.")
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
Add Comment
Please, Sign In to add comment