ios - Call a method from another UIViewController in swift 2.0 -
i have app plays song, have external class has playsound func , 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 { 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 in viewdidload of mainviewcontroller play song acces method song object:
super.viewdidload() let vc: nsobject = song() if let myvc = vc as? song { myvc.playsong() }
but doesnt play song...if put variables song mainviewcontroler playsong method , playsong() in viewdidload, works, have in external class.
any please? :)
you can create global method. create empty swift file , add 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 } { backgroundmusicplayer = try avaudioplayer(contentsofurl: newurl) backgroundmusicplayer.numberofloops = -1 backgroundmusicplayer.preparetoplay() backgroundmusicplayer.play() } catch let error nserror { print(error.description) } }
now when ever want play song call method way:
playbackgroundmusic("yoursong.mp3")
and if want go class can 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 { 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 can use way:
override func viewdidload() { super.viewdidload() let temp = song() temp.playsong() }
Comments
Post a Comment