2017-08-03 93 views
0

我正在使用此代碼來跟蹤和更新滑塊值,然後轉換爲字符串並顯示在標籤上。問題是,此代碼在模擬器上工作,但在實際的手機上崩潰。錯誤「意外地發現零,而解包可選值」。我無法弄清楚什麼可能導致這一點,任何幫助將不勝感激。Iphone上的滑塊崩潰程序,但在模擬器上工作

FUNC updateSlider(){

sliderBar.value = Float(CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime())) 
    let currentTime = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime()))) 
    let duration = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.asset.duration))) 
    //let total = currentTime - duration 

    let minutes = currentTime/60 
    let seconds = currentTime - minutes * 60 

    let minutes2 = duration/60 
    let seconds2 = duration - minutes2 * 60 

    self.lblPastTime.text = NSString(format: " %02d:%02d/%02d:%02d ",minutes2,seconds2, minutes,seconds) as String 

}

+0

它看起來像在代碼的唯一可能的選項是'self.lblPastTime'。我會建議它可能是零。 – Michael

+0

@邁克爾如果是這樣,它不會在模擬器上崩潰? –

回答

0

避免力展開變量是爲了避免這樣的錯誤的好辦法:

func updateSlider() { 

    guard let currentItem = self.audioPlayer.currentItem else { return } 
    sliderBar.value = Float(CMTimeGetSeconds(currentItem.currentTime())) 
    let currentTime = Int((CMTimeGetSeconds(currentItem.currentTime()))) 
    let duration = Int((CMTimeGetSeconds(currentItem.asset.duration))) 
    //let total = currentTime - duration 

    let minutes = currentTime/60 
    let seconds = currentTime - minutes * 60 

    let minutes2 = duration/60 
    let seconds2 = duration - minutes2 * 60 

    self.lblPastTime.text = NSString(format: " %02d:%02d/%02d:%02d ",minutes2,seconds2, minutes,seconds) as? String 

} 

使用guard let我安全地拆開包裝的變量,所以如果它是nil,函數返回。

+0

@亞歷山大感謝您的回覆。 –

0

ANSWER

只好用audioPlayer.currentTime()

相反audioPlayer.currentItem的!.currentTime()

FUNC updateSlider(){

sliderBar.value = Float(CMTimeGetSeconds(audioPlayer.currentTime())) 

// sliderBar.value = Float(CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime()))

let currentTime = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.currentTime()))) 
    let duration = Int((CMTimeGetSeconds(self.audioPlayer.currentItem!.asset.duration))) 
    //let total = currentTime - duration 

    let minutes = currentTime/60 
    let seconds = currentTime - minutes * 60 

    let minutes2 = duration/60 
    let seconds2 = duration - minutes2 * 60 

    self.lblPastTime.text = NSString(format: " %02d:%02d/%02d:%02d ",minutes2,seconds2, minutes,seconds) as String 

}

相關問題