개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.03.13 18:11

UIWindow::msg 메시지 전달 관련 오류 해결 방법

  • 앱스토어장인 2일 전 2025.03.13 18:11
  • 1
    1
저는 iOS 개발을 공부 중인데 UIWindow::msg 메시지 전달에 관해 질문을 드리겠습니다.

저는 UIWindow::msg 메시지를 사용하여 다른 뷰컨트롤러로 메시지를 전달하려고 합니다. 하지만 다음 코드를 실행했을 때, 메시지가 전달되지 않고 오류가 발생하는 것을 확인했습니다.

swift

class ViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        // 메시지 전달

        let msg = "메시지 전달"

        self.msg(msg: msg)

    }

    

    func msg(msg: String) {

        print("메시지 전달")

    }

}



이러한 오류를 해결할 방법을 알려주시면 감사하겠습니다.

    댓글목록

    profile_image
    나우호스팅  2일 전



    UIWindow::msg 메시지 전달 관련 오류는 UIWindow 클래스가 메시지 전달을 지원하지 않기 때문입니다.

    UIWindow 클래스는 뷰를 관리하는 역할을 하지만 메시지 전달을 위한 메서드는 없습니다.

    대신에, NotificationCenter를 사용하여 메시지를 전달할 수 있습니다.

    다음은 NotificationCenter를 사용하여 메시지를 전달하는 예제입니다.

    #hostingforum.kr
    swift
    
    import UIKit
    
    
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            // 메시지 전달
    
            let msg = "메시지 전달"
    
            NotificationCenter.default.post(name: .messageReceived, object: nil, userInfo: ["msg": msg])
    
        }
    
    }
    
    
    
    class SecondViewController: UIViewController {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            // 메시지 수신
    
            NotificationCenter.default.addObserver(self, selector: #selector(messageReceived), name: .messageReceived, object: nil)
    
        }
    
        
    
        @objc func messageReceived() {
    
            print("메시지 수신")
    
            if let msg = (Notification.currentNotification?.userInfo?["msg"] as? String) {
    
                print(msg)
    
            }
    
        }
    
    }
    
    


    위 예제에서는 NotificationCenter를 사용하여 메시지를 전달하고 수신하는 방법을 보여줍니다.

    메시지를 전달하는 ViewController는 NotificationCenter.default.post() 메서드를 사용하여 메시지를 전달하고, 메시지를 수신하는 SecondViewController는 NotificationCenter.default.addObserver() 메서드를 사용하여 메시지를 수신합니다.

    메시지를 수신하는 ViewController에서 메시지를 받는 방법은 Notification.currentNotification?.userInfo?["msg"] as? String를 사용하여 메시지를 받을 수 있습니다.

    이러한 방법을 사용하여 메시지를 전달하고 수신할 수 있습니다.

    2025-03-13 18:12

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 3,848건 / 51 페이지

검색

게시물 검색