swift 3.0의 NotificationCenter와 2.0의 NS NotificationCenter를 사용하여 데이터를 전달하는 방법은 무엇입니까?
구현 중입니다.socket.io
내 swift ios 앱에서.
현재 여러 패널에서 서버를 청취하고 수신 메시지를 기다리고 있습니다.나는 전화를 해서 그렇게 하고 있습니다.getChatMessage
각 패널의 기능:
func getChatMessage(){
SocketIOManager.sharedInstance.getChatMessage { (messageInfo) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//do sth depending on which panel user is
})
}
}
그러나 잘못된 접근 방식이라는 것을 알았기 때문에 변경해야 합니다. 이제 수신 메시지를 한 번만 듣고 메시지가 오면 이 메시지를 수신하는 패널에게 전달합니다.
그래서 NS Notification Center를 통해 수신 메시지를 전달하고 싶습니다.지금까지 저는 어떤 일이 일어났다는 정보를 전달할 수 있었지만, 데이터 자체는 전달할 수 없었습니다.저는 그것을 하고 있었습니다.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)
다음과 같은 기능이 있었습니다.
func showSpinningWheel(notification: NSNotification) {
}
그리고 제가 부르고 싶을 때마다 저는 다음과 같이 했습니다.
NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)
그럼 어떻게 물건을 건네줄 수 있나요?messageInfo
호출되는 함수에 포함시킬 수 있습니까?
스위프트 2.0
다음을 사용하여 정보 전달userInfo
이것은 선택적 유형 사전입니다.[NSObject : AnyObject]?
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
// For swift 4.0 and above put @objc attribute in front of function Definition
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Swift 3.0, 4.0, 5.0 이상 버전
이제 userInfo는 [AnyHashable:[Any]? 인수로, Swift에서 사전 리터럴로 제공합니다.
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
// For swift 4.0 and above put @objc attribute in front of function Definition
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
참고: 알림 "이름"은 더 이상 문자열이 아니라 알림 유형입니다.이름, 그래서 우리가 사용하는 이유는NSNotification.Name(rawValue: "notificationName")
알림을 연장할 수 있습니다.자체 사용자 지정 알림으로 이름을 지정합니다.
extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}
// and post notification like this
NotificationCenter.default.post(name: .myNotification, object: nil)
스위프트 3용
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
스위프트 4용
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
@objc func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
안녕 @sahil 나는 당신의 답변을 swift 3으로 업데이트합니다.
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
도움이 되길 바랍니다.감사해요.
이것이 스위프트 5에서 저에게 효과가 있었던 것입니다.
NotificationCenter.default.addObserver(self,
selector: #selector(handleMassage),
name: Notification.Name("NotificationName"),
object: nil)
통지를 처리하는 방법:
@objc func handleMassage(notification: NSNotification) {
if let dict = notification.object as? NSDictionary {
if let myMessage = dict["myMessage"] as? String{
myLabel.text = myMessage
}
}
}
다음과 같이 게시했습니다.
let dic = ["myMessage": "testing"]
NotificationCenter.default.post(name: Notification.Name("NotificationName"), object: dic)
신속한 5.5(회피 포함)#selector()
:
먼저 이름을 선언합니다.
extension Notification.Name {
static let prettyName = Notification.Name("MyPrettyName")
}
다음은 관찰자를 추가하는 것입니다(대기열 주의).
// For example transferred data should implement protocol
protocol PrettyDelegate {
func doSomethingAwesome()
}
// Here is the way how we can subscribe as observer
NotificationCenter.default.addObserver(forName: .prettyName, object: nil, queue: nil) { [weak self] notif in
guard let self = self else { return } // Because self used more than once
if let userInfo = notif.userInfo,
let delegate = userInfo["pretty"] as? PrettyDelegate {
self.delegate = delegate
}
self.makePretty() // Here we can do anything
}
마지막으로, 우리는 다른 개체로부터 알림을 게시할 수 있습니다.
// Here I'll illustrate how to pass optional value as userInfo
var userInfo: [AnyHashable : Any]?
if let prettyDelegate = self as? PrettyDelegate {
userInfo = ["pretty": prettyDelegate]
}
NotificationCenter.default.post(name: .prettyName, object: nil, userInfo: userInfo)
참고: 관찰자가 더 이상 필요하지 않을 때 관찰자를 제거하는 것을 잊지 마십시오.
이것이 제가 구현하는 방법입니다.
let dictionary = self.convertStringToDictionary(responceString)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)
swift 4.2에서 NSNotification을 사용하여 코드를 표시하고 숨기기 위해 다음 코드를 사용했습니다.
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardheight = keyboardSize.height
print(keyboardheight)
}
}
언급URL : https://stackoverflow.com/questions/36910965/how-to-pass-data-using-notificationcenter-in-swift-3-0-and-nsnotificationcenter
'programing' 카테고리의 다른 글
pgAdmin을 사용하여 테이블 덤프(.sql) 내보내기 및 가져오기 (0) | 2023.05.20 |
---|---|
ASP.NET 애플리케이션을 실시간 서버에 어떻게 배포합니까? (0) | 2023.05.20 |
Swift 코드를 Objective-C로 가져오려면 어떻게 해야 합니까? (0) | 2023.05.20 |
Eclipse에서 문자열 대소문자 변경 (0) | 2023.05.20 |
문자열에 대한 인쇄와 동등한 값을 얻습니다.Excel 형식 (0) | 2023.05.20 |