[英]how can I access field/method from another UIViewController in Swift?
[英]Call a method from another UIViewController in swift 2.0
我有一个播放歌曲的应用程序,有一个具有playSound函数和所需所有变量的外部类:
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()
}
然后在我的mainViewController的ViewDidLoad中播放歌曲,并从Song对象中访问该方法:
super.viewDidLoad()
let vc: NSObject = Song()
if let myVc = vc as? Song {
myVc.playSong()
}
但这不会播放歌曲...如果我也使用playSong方法将Song中的所有变量也放置到mainViewControler中,并在viewDidLoad中说playSong(),它可以工作,但我想在外部类中使用它。
有什么帮助吗? :)
您可以创建一个全局方法。 创建一个空的swift文件,并在其中添加以下代码:
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)
}
}
现在,当您想播放任何歌曲时,只需以这种方式调用该方法:
playBackgroundMusic("yourSong.mp3")
如果您想上课,可以按照以下方式进行:
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()
}
}
在其他课程中,您可以通过以下方式使用它:
override func viewDidLoad() {
super.viewDidLoad()
let temp = Song()
temp.playSong()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.