저는 두 개의 ViewController가 있습니다 : ViewController
및 SecondViewController
입니다. 이 두 ViewController에 관찰자를 추가했습니다. ViewController
에서 알림을 게시 할 IBAction도 정의했습니다. 두 ViewController의 클로저를 통해 알림을 처리합니다. 그러나 ViewController
의 폐쇄 만 호출됩니다. SecondViewController
에있는 클로저 (심지어 전체 코드까지)가 호출되지 않습니다 (디버거를 사용하여 검사했습니다). 클로저는 print 문만을 포함합니다. 가 여기 내 코드입니다Observer가 NotificationCenter Swift 4.0을 사용하여 호출되지 않습니다.
//ViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
print("I'm the : \(type(of: self))")
}
}
@IBAction func sendNotification(_ sender: UIButton) {
let nc = NotificationCenter.default
nc.post(name: Notification.Name(rawValue:"MyNotification"), object: nil, userInfo: ["message":"Hello there!", "Date:":Date()])
}
}
ScondViewController
//SecondViewController
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in
print("I'm the: \(type(of: self))")
}
}
}
의 ViewController의 폐쇄를 호출하지만 SecondViewController에서 폐쇄하지 않는됩니다. 어쩌면 그 이유는 알림을 게시하기 전에 SecondViewController가 초기화되지 않는다는 것입니다. 그러나 해결책은 어떻게 생겼습니까? 도움을 주시면 감사하겠습니다.
알림을 보내거나 게시 할 때 메모리에 SecondViewController 인스턴스가 있습니까? –
전화가 걸리지 않습니다. 이 통지를 지연과 함께 게시해야합니다. – Mannopson
내가 게시하기 전에 SVC가 초기화되지 않았기 때문에 바로 호출되지 않습니다. 'ViewController'의 viewDidLoad에'let svc = SecondViewController()'를 추가하여 기본 init을 호출했지만 아무 효과가 없습니다. SVC의 클로저가 호출되지 않습니다. 누구나 해결 방법을 알고 있습니까? – user1895268