简体   繁体   中英

Call a method from another UIViewController in swift 2.0

I have an app which plays a song, I have an external class which has a playSound func and all the variables needed:

class Song: NSObject {

    var audioPlayer: AVAudioPlayer!
    var deviceCurrentTime: NSTimeInterval!

    func playSong() {

        let sound = NSBundle.mainBundle().pathForResource("song", ofType: "mp3")
        let soundData = NSData(contentsOfFile: sound!)
        //  self.audioPlayer = AVAudioPlayer(data: soundData!) throws

        self.audioPlayer = nil
        do {
            self.audioPlayer = try AVAudioPlayer(data: soundData!)
        }
        catch {
            print("Handle \(error) here")
        }

        let delay:NSTimeInterval = 0.0//100ms
        var playtime:NSTimeInterval
        playtime = audioPlayer.deviceCurrentTime + delay

        self.audioPlayer?.playAtTime(playtime)
        self.audioPlayer?.play()


    }

and then in ViewDidLoad of my mainViewController i would like to play the song an acces the method from my Song object:

    super.viewDidLoad()

    let vc: NSObject = Song()
    if let myVc = vc as? Song {
        myVc.playSong()
    }

but that doesnt play the song...if i put all the variables from Song to mainViewControler also with the playSong method and say playSong() in viewDidLoad, it works, but i would like to have it in external class.

Any help please? :)

You can create a global method. Create a empty swift file and add this code in it:

import Foundation
import AVFoundation


var backgroundMusicPlayer = AVAudioPlayer()

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch let error as NSError {
        print(error.description)
    }
}

Now when ever you want to play any song just call that method this way:

playBackgroundMusic("yourSong.mp3")

And if you want to go with your class then you can do it this way:

import Foundation
import AVFoundation

var audioPlayer: AVAudioPlayer!
var deviceCurrentTime: NSTimeInterval!

class Song: NSObject {

    func playSong() {

        let sound = NSBundle.mainBundle().pathForResource("We_Are_One_Ole_Ola_", ofType: "mp3")
        let soundData = NSData(contentsOfFile: sound!)
        //  self.audioPlayer = AVAudioPlayer(data: soundData!) throws

        audioPlayer = nil
        do {
            audioPlayer = try AVAudioPlayer(data: soundData!)
        }
        catch {
            print("Handle \(error) here")
        }

        let delay:NSTimeInterval = 0.0//100ms
        var playtime:NSTimeInterval
        playtime = audioPlayer.deviceCurrentTime + delay

        audioPlayer?.playAtTime(playtime)
        audioPlayer?.play()

    }
}

In other class you can use it this way:

override func viewDidLoad() {
    super.viewDidLoad()

    let temp = Song()
    temp.playSong()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM