Swift 3.0의 NotificationCenter와 Swift 2.0의 NSNotificationCenter를 사용하여 데이터를 전달하는 방법은 무엇입니까?
socket.io
내 빠른 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
})
}
}
그러나 나는 그것이 잘못된 접근 방식이라는 것을 알았고 그것을 변경해야합니다. 이제 들어오는 메시지를 한 번만 듣고 메시지가 오면이 메시지를 듣고있는 모든 패널 에이 메시지를 전달하려고합니다.
그래서 NSNotificationCenter를 통해 들어오는 메시지를 전달하고 싶습니다. 지금까지 어떤 일이 일어났다는 정보를 전달할 수 있었지만 데이터 자체는 전달할 수 없었습니다. 나는 다음과 같이하고 있었다.
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
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)
// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)
// handle notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Swift 3.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
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
참고 : 알림 "이름"은 더 이상 문자열이 아니지만 Notification.Name 유형이므로 NSNotification.Name(rawValue:"notificationName")
자체 사용자 지정 알림으로 Notification.Name을 사용 하고 확장 할 수 있습니다.
extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}
// and post notification like this
NotificationCenter.default.post(name: .myNotification, object: nil)
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
}
}
}
Swift 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 저는 신속한 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
}
}
}
도움이 되었기를 바랍니다. 감사
let dictionary = self.convertStringToDictionary (responceString)
NotificationCenter.default.post (name : NSNotification.Name (rawValue : "SOCKET_UPDATE"), 객체 : 사전)
In swift 4.2 I used following code to show and hide code using NSNotification
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardheight = keyboardSize.height
print(keyboardheight)
}
}
'program story' 카테고리의 다른 글
Node.js에서 거대한 로그 파일 구문 분석-한 줄씩 읽기 (0) | 2020.08.17 |
---|---|
AngularJS에서 ng-pristine과 ng-dirty의 차이점은 무엇입니까? (0) | 2020.08.17 |
행렬을 1 차원 배열로 변환 (0) | 2020.08.17 |
Bash 스크립트는 빈 줄에 "Command Not Found"를 인쇄합니다. (0) | 2020.08.17 |
SQL 기존 열에 외래 키 추가 (0) | 2020.08.16 |