My code is randomly generating 2 separate images on the same interface controller. I need to check if the images match each other, but i'm unsure how to go about this as they are being randomly generated. I have tried writing if statements such as:
if blueColour.setBackgroundImageNamed("colour\(randomImage).jpg") == mainBackgroundColour.setBackgroundImageNamed("mainColour\(randomMainBackground).jpg") {
println("they match")
} else {
println("they dont match")
}
but it doesn't seem to work, i get an error saying "binary operator '==' cannot be applied to two Void operands"
My code is below:
#IBOutlet var blueColour: WKInterfaceButton!
#IBOutlet var pinkColour: WKInterfaceButton!
#IBOutlet var greenColour: WKInterfaceButton!
#IBOutlet var yellowColour: WKInterfaceButton!
#IBOutlet var mainBackgroundColour: WKInterfaceGroup!
#IBOutlet var scoreLabel: WKInterfaceLabel!
var randomImage = UInt32()
var randomMainBackground = UInt32()
#IBAction func onePressedTest() {
if blueColour.setBackgroundImageNamed("colour\(randomImage).jpg") == mainBackgroundColour.setBackgroundImageNamed("mainColour\(randomMainBackground).jpg") {
println("they match")
} else {
println("they dont match")
}
randomImage = arc4random_uniform(4)
blueColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomImage = arc4random_uniform(4)
pinkColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomImage = arc4random_uniform(4)
greenColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomImage = arc4random_uniform(4)
yellowColour.setBackgroundImageNamed("colour\(randomImage).jpg")
randomMainBackground = arc4random_uniform(4)
mainBackgroundColour.setBackgroundImageNamed("mainColour\(randomMainBackground).jpg")
}
NEW AMENDED CODE 20.04.2015:
import WatchKit
import Foundation
protocol WKInterfaceComparableImage {
func getImage()->UIImage;
func equalsImage(comparableWKObject:WKInterfaceComparableImage)->Bool;
}
class WKInterfaceButtonComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class WKInterfaceGroupComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class ImageProvide {
private let MAX_RANDOM_NUMBER:UInt32 = 4
static let shared:ImageProvide = ImageProvide();
var images:[UIImage];
private init() {
images = [];
for i in 1...MAX_RANDOM_NUMBER {
//get image with the best way to you
images.append(UIImage(named: "colour\(i).jpg")!);
}
}
func getRandomImage()->UIImage {
let randomImage = arc4random_uniform(MAX_RANDOM_NUMBER);
return getImage(id: Int(randomImage));
}
func getImage(#id:Int)->UIImage {
return images[id];
}
}
class InterfaceController: WKInterfaceController {
#IBOutlet var blueColour: WKInterfaceButtonComparable!
#IBOutlet var pinkColour: WKInterfaceButtonComparable!
#IBOutlet var greenColour: WKInterfaceButtonComparable!
#IBOutlet var yellowColour: WKInterfaceButtonComparable!
#IBOutlet var mainBackgroundColour: WKInterfaceGroupComparable!
#IBOutlet var scoreLabel: WKInterfaceLabel!
var randomImage = UInt32()
var randomMainBackground = UInt32()
var score:Int = 1
#IBAction func onePressedTest() {
if blueColour.equalsImage(mainBackgroundColour) || pinkColour.equalsImage(mainBackgroundColour) || greenColour.equalsImage(mainBackgroundColour) || yellowColour.equalsImage(mainBackgroundColour) {
println("they match")
scoreLabel.setText("\(score)")
score++
} else {
println("they dont match")
}
blueColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
pinkColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
greenColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
yellowColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
mainBackgroundColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
I made an example what I think can help you find the way to resolve your issues, I created class custom with comparable power to help your work. I do it very fast, and I don't have way to test for you, but you can see the concept to help you create a solution. I hope so helped you with my example.
ComparableImage is the key to compare, this protocol can do your mission.
WKInterfaceButtonComparable extends WKInterfaceButton and with this you can save the current image to compare after, I did same with WKInterfaceGroupComparable.
ImageProvide is important because this will manage your images, there you need code your logic about images and with this Singleton you can preload your images and send to your WK components. I hope it help too.
protocol WKInterfaceComparableImage {
func getImage()->UIImage;
func equalsImage(comparableWKObject:WKInterfaceComparableImage)->Bool;
}
class WKInterfaceButtonComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class WKInterfaceGroupComparable : WKInterfaceButton, WKInterfaceComparableImage {
private var image:UIImage?;
override func setBackgroundImage(image: UIImage?) {
self.image = image;
super.setBackgroundImage(image);
}
func equalsImage(comparableWKObject: WKInterfaceComparableImage)->Bool {
return self.image === comparableWKObject.getImage();
}
func getImage() -> UIImage {
return image!;
}
}
class ImageProvide {
private let MAX_RANDOM_NUMBER:UInt32 = 4
static let shared:ImageProvide = ImageProvide();
var images:[UIImage];
private init() {
images = [];
for i in 1...MAX_RANDOM_NUMBER {
//get image with the best way to you
images.append(UIImage(named: "colour\(i).jpg")!);
}
}
func getRandomImage()->UIImage {
let randomImage = arc4random_uniform(MAX_RANDOM_NUMBER);
return getImage(id: Int(randomImage));
}
func getImage(#id:Int)->UIImage {
return images[id];
}
}
class InterfaceController: WKInterfaceController {
#IBOutlet var blueColour: WKInterfaceButtonComparable!
#IBOutlet var pinkColour: WKInterfaceButtonComparable!
#IBOutlet var greenColour: WKInterfaceButtonComparable!
#IBOutlet var yellowColour: WKInterfaceButtonComparable!
#IBOutlet var mainBackgroundColour: WKInterfaceGroupComparable!
#IBOutlet var scoreLabel: WKInterfaceLabel!
var randomImage = UInt32()
var randomMainBackground = UInt32()
var score:Int = 1
#IBAction func onePressedTest() {
if blueColour.equalsImage(mainBackgroundColour) {
println("they match")
} else {
println("they dont match")
}
blueColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
pinkColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
greenColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
yellowColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
mainBackgroundColour.setBackgroundImage(ImageProvide.shared.getRandomImage())
}
}
Related
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var chargeLabel: UILabel!
#IBOutlet weak var bigDogLabel: UILabel!
#IBOutlet weak var cafeImageView: UIImageView!
override func viewDidLoad() {
}
struct DogCafe{
var name: String
var charge: Int
var bigDog: Bool
var cafeImage: UIImage
init(name: String, charge: Int, bigDog: Bool, cafeImage: UIImage) {
self.name = name
self.charge = charge
self.cafeImage = cafeImage
self.bigDog = bigDog
}
func message() {
nameLabel.text = "카페 \(name) 입니다"
chargeLabel.text = "입장료는 \(charge) 입니다"
cafeImageView.image = cafeImage
if bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
}
}
#IBAction func ohdodokButton(_ sender: UIButton) {
let dogCafe = DogCafe(name: "카페 오도독", charge: 3500, bigDog: true, cafeImage: #imageLiteral(resourceName: "ohdodok"))
dogCafe.message()
}
#IBAction func meltingButton(_ sender: UIButton) {
let dogCafe2 = DogCafe(name: "멜팅", charge: 5000, bigDog: false, cafeImage: #imageLiteral(resourceName: "melting"))
dogCafe2.message()
}
}
func message() {
nameLabel.text = "카페 \(name) 입니다"
chargeLabel.text = "입장료는 \(charge) 입니다"
cafeImageView.image = cafeImage
if bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
Instance member 'nameLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'chargeLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'cafeImageView' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'bigDogLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
you can use like below
#IBAction func ohdodokButton(_ sender: UIButton) {
let dogCafe = DogCafe(name: "카페 오도독", charge: 3500, bigDog: true, cafeImage: #imageLiteral(resourceName: "ohdodok"))
setCurrentDogAttributes(currentDog: dogCafe)
}
#IBAction func meltingButton(_ sender: UIButton) {
let dogCafe2 = DogCafe(name: "멜팅", charge: 5000, bigDog: false, cafeImage: #imageLiteral(resourceName: "melting"))
setCurrentDogAttributes(currentDog: dogCafe)
}
func setCurrentDogAttributes(currentDog:DogCafe){
nameLabel.text=currentDog.name
//Set your Values Here
}
Your approach is wrong. You need to read up on separation of concerns. I'd also suggest reading up on the MVC (Model View Controller) design pattern, which is a pretty common way to do development on iOS.
In your code, DogCafe is a model object. It contains data that you want your app to manipulate and display.
A model object should not know anything about how it is being used. It just holds data.
Your view controller should take the model object and display it to its views. One way to handle that is to add a display(cafe:) method to your view controller:
class ViewController: UIViewController {
// The rest of your view controller variables and functions would go here...
func display(cafe: DogCafe) {
nameLabel.text = "카페 \(cafe.name) 입니다"
chargeLabel.text = "입장료는 \(cafe.charge) 입니다"
cafeImageView.image = cafe.cafeImage
if cafe.bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
}
}
In my PlayerViewController, I am trying to play a song that is selected from my Table view. Also this first line of code is in another view controller. What would be a better way to write the player.playStream line?
EDIT: PlayerViewController
#IBOutlet weak var playPauseButton: UIButton!
var player: Player!
var song: [Song] = []
let indexPath = IndexPath()
var MusicPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
player = Player()
setSession()
UIApplication.shared.beginReceivingRemoteControlEvents()
becomeFirstResponder()
NotificationCenter.default.addObserver(self, selector: Selector(("handleInterruption")), name: AVAudioSession.interruptionNotification, object: nil)
player.playStream(fileUrl: "http://127.0.0.1/musicfiles" + song[indexPath.row].getName())
changePlayButton()
}
Song.swift:
class Song {
var id = Int()
var name = String()
var year = Int()
var numLikes = Int()
var numPlays = Int()
init?(id:String, name:String, year:String, numlikes:String, numplays:String) {
self.id = Int(id)!
self.name = name
self.year = Int(year)!
self.numLikes = Int(numLikes)
self.numPlays = Int(numplays)!
}
func getId() -> Int {
return id
}
func getName() -> String {
return name
}
func getYear() -> Int {
return year
}
func getNumLikes() -> Int {
return numLikes
}
func getNumPlays() -> Int {
return numPlays
}
}
I am struggling to comprehend how to cache images in my listview that I have fetched from Firebase. I have checked online and most of the solutions are somewhat different from the style of code I am writing so find it difficult to transfer over. Any solutions would be grateful for the class I have provided below.
class StaffListTableViewCell: UITableViewCell {
#IBOutlet weak var staffFirstAndLastName: UILabel!
#IBOutlet weak var JobTitle: UILabel!
#IBOutlet weak var staffImageView: UIImageView!
var databaseRef: DatabaseReference {
return Database.database().reference()
}
var storageRef: Storage {
return Storage.storage()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell(teacher: StaffListsSTRUCT) {
//this line of code helps sets the imageviews in the list view to nil before loading.
self.staffImageView.image = nil
self.staffFirstAndLastName.text = teacher.staffName
self.JobTitle.text = teacher.staffJobTitle
let imageURL = teacher.staffImageViewString!
self.storageRef.reference(forURL: imageURL).getData(maxSize: 1 * 1024 * 1024, completion: { (imgData,
error) in
if error == nil {
DispatchQueue.main.async {
if let data = imgData {
self.staffImageView.image = UIImage(data: data)
}
}
} else {
print(error!.localizedDescription)
}
})
}
}
so I'm new to coding and I've been doing practice games a such to build my skills. I've created this word guessing game and I'm trying to make the game show the word after all guesses have been used up. However, the program doesn't read the code I write to set the label to display the answer. Here is the code I've written so far:
class ViewController: UIViewController {
var listOfWords = ["ladybug", "program", "computer", "language", "glorious", "incandescent"]
let incorrectMovesAllowed = 7
var totalWins = 0 {
didSet {
newRound()
}
}
var totalLosses = 0 {
didSet {
newRound()
}
}
#IBOutlet var letterButtons: [UIButton]!
#IBAction func buttonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)!
let letter = Character(letterString.lowercased())
currentGame.playerGuessed(letter: letter)
updateUI()
updateGameState()
}
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var correctWordLabel: UILabel!
#IBOutlet weak var treeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
newRound()
// Do any additional setup after loading the view, typically from a nib.
}
func enableLetterButtons (_enable: Bool){
for button in letterButtons {
button.isEnabled = _enable
}
}
var currentGame : Game!
func newRound() {
if !listOfWords.isEmpty{
let newWord = listOfWords.removeFirst()
currentGame = Game (word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
enableLetterButtons(_enable: true)
updateUI()
} else {
enableLetterButtons (_enable: false)
}
}
func updateUI() {
var letters = [String] ()
for letter in currentGame.formattedWord.characters {
letters.append(String(letter))
}
let wordWithSpacing = letters.joined(separator: " ")
correctWordLabel.text = wordWithSpacing
scoreLabel.text = "Wins: \(totalWins), Losses:\(totalLosses)"
treeImageView.image = UIImage (named: "Tree \(currentGame.incorrectMovesRemaining)")
}
func updateGameState(){
var letters = [String] ()
for letter in currentGame.word.characters {
letters.append(String(letter))
}
let theAnswer = letters.joined(separator: " ")
if currentGame.incorrectMovesRemaining == 0 {
correctWordLabel.text = theAnswer
Thread.sleep(forTimeInterval: 3)
totalLosses += 1
} else if currentGame.word == currentGame.formattedWord {
totalWins += 1
} else {
updateUI()
}
}
}
In addition, I have a structure that is written like this:
import Foundation
struct Game {
var word : String
var incorrectMovesRemaining : Int
var guessedLetters: [Character]
mutating func playerGuessed (letter: Character){
guessedLetters.append(letter)
if !word.characters.contains(letter){
incorrectMovesRemaining -= 1
}
}
var formattedWord: String {
var guessedWord = ""
for letter in word.characters {
if guessedLetters.contains(letter) {
guessedWord += "\(letter)"
} else {
guessedWord += "_"
}
}
return guessedWord
}
}
You need to redraw your UI, this is done with self.setNeedsDisplay(). It notifies the system that the view's contents needs to be redrawn. In your updateUI() you can add this.
Regarding setNeedsDisplay you can get more information here
class ViewController: UIViewController {
var listOfWords = ["ladybug", "program", "computer", "language", "glorious", "incandescent"]
let incorrectMovesAllowed = 7
var totalWins = 0 {
didSet {
newRound()
}
}
var totalLosses = 0 {
didSet {
newRound()
}
}
#IBOutlet var letterButtons: [UIButton]!
#IBAction func buttonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)!
let letter = Character(letterString.lowercased())
currentGame.playerGuessed(letter: letter)
updateUI()
updateGameState()
}
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var correctWordLabel: UILabel!
#IBOutlet weak var treeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
newRound()
// Do any additional setup after loading the view, typically from a nib.
}
func enableLetterButtons (_enable: Bool){
for button in letterButtons {
button.isEnabled = _enable
}
}
var currentGame : Game!
func newRound() {
if !listOfWords.isEmpty{
let newWord = listOfWords.removeFirst()
currentGame = Game (word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
enableLetterButtons(_enable: true)
updateUI()
} else {
enableLetterButtons (_enable: false)
}
}
func updateUI() {
var letters = [String] ()
for letter in currentGame.formattedWord.characters {
letters.append(String(letter))
}
let wordWithSpacing = letters.joined(separator: " ")
correctWordLabel.text = wordWithSpacing
scoreLabel.text = "Wins: \(totalWins), Losses:\(totalLosses)"
treeImageView.image = UIImage (named: "Tree \(currentGame.incorrectMovesRemaining)")
self.setNeedsDisplay()
}
func updateGameState(){
var letters = [String] ()
for letter in currentGame.word.characters {
letters.append(String(letter))
}
let theAnswer = letters.joined(separator: " ")
if currentGame.incorrectMovesRemaining == 0 {
correctWordLabel.text = theAnswer
Thread.sleep(forTimeInterval: 3)
totalLosses += 1
} else if currentGame.word == currentGame.formattedWord {
totalWins += 1
} else {
updateUI()
}
}
}
Create a variable that will keep track of how many times you have guessed wrong. Then you can do this:
Use a while statement:
while numberOfTimesGuessedWrong <= 7{
}
//when you have guessed incorrectly 7 times, the compiler will move here:
wordLabel.text = "\(correctAnswer)"
So when you guess incorrectly 7 times, on the 8th time, it will then show the correct answer.
I'm facing a very unique situation, AVPlayer is trying to stream a URL that it loads multiple times (I see in control centre) before eventually playing it, after a long delay of about 120 seconds or so (sometimes more). I don't know why that is happening. I use a singleton instance of KDEAudioPlayer - any help would be appreciated.
KDEAudioPlayer Code:
import UIKit
import KDEAudioPlayer
var urlToPlay : NSURL!
var titleTrackBeingPlayed = String?()
class MediaPlayerViewController: FXBlurView, AudioPlayerDelegate {
//MARK: Variables
var seekToTime = NSTimeInterval()
var streaming = true
var timer:NSTimer?
var change:CGFloat = 0.01
//MARK: Connections
#IBOutlet weak var loadingActivityIndicator: UIActivityIndicatorView!
#IBOutlet weak var streamingFromServerLabel: UILabel!
#IBOutlet weak var timelineSlider: UISlider!
#IBOutlet weak var totalTimeLabel: UILabel!
#IBOutlet weak var nowTimeLabel: UILabel!
#IBOutlet weak var toggleButton: UIButton!
#IBOutlet weak var volumeControlSlider: UISlider!
#IBOutlet weak var titleLabel: UILabel!
//MARK: Actions
#IBAction func endTrackPlayerButtonPressed(sender: UIButton) {
//TODO: R&D how to dismiss.
print("media player view to be dismissed")
if let viewWithTag = self.viewWithTag(1089) {
print("Tag 1089")
Singleton.stop()
viewWithTag.removeFromSuperview()
}
}
#IBAction func timelineSliderValueChanged(sender: UISlider) {
Singleton.pause()
Singleton.seekToTime(NSTimeInterval(sender.value))
timelineSlider?.setValue(sender.value, animated: true)
Singleton.resume()
}
#IBAction func playPauseButtonPressed(sender: UIButton) {
toggle()
}
//MARK: Initializer for Class
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.tintColor = UIColor.clearColor()
if Singleton.isPlaying {
Singleton.isPlaying = false
}
playerSetup()
toggle()
}
//MARK: Setup for Audio Player
func playerSetup() {
Singleton.playItemWithUrl(urlToPlay)
Singleton.player.delegate = self
timelineSlider?.continuous = true
self.titleLabel?.text = titleTrackBeingPlayed
}
internal func refreshAudioView(_ :NSTimer) {
}
func toggle(){
if Singleton.isPlaying {
pauseTrack()
toggleButton.setImage(UIImage(named: "Play"), forState: .Normal)
}
else if !Singleton.isPlaying {
playTrack()
toggleButton?.setImage(UIImage(named: "Pause"), forState: .Normal)
}
}
func audioPlayer(audioPlayer: AudioPlayer, willStartPlayingItem item: AudioItem) {
titleLabel.text = titleTrackBeingPlayed
}
func audioPlayer(audioPlayer: AudioPlayer, didFindDuration duration: NSTimeInterval, forItem item: AudioItem) {
totalTimeLabel?.text = makeTimeString(Float(duration))
timelineSlider?.maximumValue = Float(duration)
timelineSlider?.minimumValue = 0.0
self.titleLabel?.text = titleTrackBeingPlayed
}
func audioPlayer(audioPlayer: AudioPlayer, didUpdateProgressionToTime time: NSTimeInterval, percentageRead: Float) {
timelineSlider?.setValue(Float(time), animated: true)
nowTimeLabel?.text = makeTimeString(Float(time))
Singleton.player.volume = volumeControlSlider.value
seekToTime = time
}
override func remoteControlReceivedWithEvent(event: UIEvent?) {
if let event = event {
Singleton.player.remoteControlReceivedWithEvent(event)
self.canBecomeFirstResponder()
}
}
func audioPlayer(audioPlayer: AudioPlayer, didChangeStateFrom from: AudioPlayerState, toState to: AudioPlayerState) {
if to == .Playing {
if streaming {
streamingFromServerLabel.hidden = false
loadingActivityIndicator.hidden = true
toggleButton?.setImage(UIImage(named: "Pause"), forState: .Normal)
}
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TrackMediaPlayerViewController.refreshAudioView(_:)), userInfo: nil, repeats: true)
}
else if to == .Buffering || to == .WaitingForConnection {
loadingActivityIndicator.hidden = false
}
else {
streamingFromServerLabel.hidden = true
}
}
func playTrack() {
if seekToTime > 0.0 {
Singleton.resume()
} else {
Singleton.play()
}
Singleton.isPlaying = true
}
func pauseTrack() {
Singleton.pause()
Singleton.isPlaying = false
}
//MARK: Convert NSTime to String
func makeTimeString(value:Float) -> String
{
if value == 0 || value.isNaN
{
return "00:00"
}
let hr = (Int)(value / 3600)
let min = (Int)((value % 3600) / 60)
let sec = (Int)((value % 3600) % 60)
let timestamp = String(format:"%d:%02d.%02d", hr, min, sec)
return timestamp
}
}
Singleton Code:
import Foundation
import UIKit
import KDEAudioPlayer
class Singleton: AudioPlayerDelegate {
static let shareInstance = DarsPlayerSingleton()
static let player = AudioPlayer()
static var isPlaying = Bool()
private init (){
}
static func playItemWithUrl(url: NSURL) {
let item = AudioItem(mediumQualitySoundURL: url)
player.playItem(item!)
}
static func play() {
player.resume()
isPlaying = true
}
static func pause() {
player.pause()
isPlaying = false
}
static func stop() {
player.stop()
}
static func seekToTime(time: NSTimeInterval){
player.seekToTime(time)
}
static func resume() {
player.resume()
}
}