【问题标题】:Calling ViewController's Method from App Delegate从 App Delegate 调用 ViewController 的方法
【发布时间】:2015-11-14 18:03:29
【问题描述】:

在我的 ViewController 收件箱中,我想从我的 App Delegate 调用 playAudio() 方法。

这就是方法。

func playAudio(){

        let nowPlaying = MPNowPlayingInfoCenter.defaultCenter()

        let albumArtWork = MPMediaItemArtwork(image: UIImage(named: "testImage.jpg")!)

        nowPlaying.nowPlayingInfo = [MPMediaItemPropertyTitle:"Sonnnngggg",
            MPMediaItemPropertyArtist:"Arrrtttiiiissstttt",
            MPMediaItemPropertyArtwork:albumArtWork]
        audioPlayer.play()

    }

我想从我的 App Delegate 中调用它...

if event!.subtype == UIEventSubtype.RemoteControlPlay {
                print("received remote play")
                //audioPlayer.play()
                Inbox.playAudio()
            }

一个问题是,因为我有一个 audioPlayer 和我的收件箱 ViewController 中的所有内容,并且它可能已经在播放音频,所以创建一个收件箱实例来调用 playAudio() 是没有意义的。所以,如果 Swift 中有任何解决方法,请告诉我。

谢谢, 利亚姆

【问题讨论】:

    标签: ios swift appdelegate


    【解决方案1】:

    在 AppDelegate 中更改为:

    if event!.subtype == UIEventSubtype.RemoteControlPlay {
                print("received remote play")
                //audioPlayer.play()
                NSNotificationCenter.defaultCenter().postNotificationName("RemotePlayPressed", object: self)
            }
    

    然后在 Inbox 视图控制器的 viewDidLoad 中添加:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playAudio", name: "RemotePlayPressed", object: nil)
    

    还要补充:

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

    到收件箱视图控制器。

    【讨论】:

      【解决方案2】:

      在您的视图控制器中,您可以通过

      访问您的 appdelegate

      (UIApplication.sharedApplication().delegate as! AppDelegate).playAudio()

      【讨论】:

      • 我想通过我的应用委托调用我的 ViewController 的函数。
      • 它嵌套在一个导航控制器中……它是最远的分支。该函数只是一个普通函数,还有其他方法。
      【解决方案3】:

      你可以实例化 AppDelegate 并调用你想要的函数

      let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
      appDelegate.someFunction()
      

      但这似乎不是一个好习惯......

      NSNotificationCenter:

      在你想调用函数的地方使用这段代码:

      NSNotificationCenter.defaultCenter().addObserver(self, selector: "anotherFunction", name: "SomeNotification", object: nil)
      

      anotherFunction改成你要调用的函数名。

      在 AppDelegate 上:

      NSNotificationCenter.defaultCenter().postNotificationName("SomeNotification", object: nil)
      

      【讨论】:

      • 我想通过我的应用委托调用我的 ViewController 的函数。
      • 您可以使用 NSNotificationCenter 来实现这一点。
      • 你能编辑你的答案来显示这个吗?我有点新。
      猜你喜欢
      • 2014-09-16
      • 2011-07-02
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多