![](/img/trans.png)
[英]Swift : fatal error: unexpectedly found nil while unwrapping an Optional value
[英]xcode9 swift4 Fatal error: Unexpectedly found nil while unwrapping an Optional value
應用啟動時,我試圖播放mp3文件(5秒),但不斷出現錯誤:
線程1:致命錯誤:展開一個可選值時意外地找到零
import UIKit
import AudioToolbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//create SystemSoundID
var soundID:SystemSoundID = 0
let path = Bundle.main.path(forResource: "iPhone100Voice", ofType: "mp3")
let baseURL = NSURL(fileURLWithPath: path!)
AudioServicesCreateSystemSoundID(baseURL, &soundID)
//play
AudioServicesPlaySystemSound(soundID)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
誰能解釋為什么以及如何解決這個問題?
檢查以下幾點,所有條件都必須為真:
Target Membership
復選框(要獲取它,請選擇文件並按⌥⌘1 ) iPhone100Voice.mp3
)? 請檢查您的文件名,也許文件名不正確或捆綁包中沒有
因此,請檢查帶有擴展名的文件名。
if let
或guard
unwrap
路徑,請使用:
override func viewDidLoad() {
super.viewDidLoad()
var soundID:SystemSoundID = 0
if let path = Bundle.main.path(forResource: "iPhone100Voice", ofType: "mp3") {
let baseURL = NSURL(fileURLWithPath: path)
AudioServicesCreateSystemSoundID(baseURL, &soundID)
AudioServicesPlaySystemSound(soundID)
} else {
let alert = UIAlertController(title: "Alert", message: "File not found in your bundle", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
播放視頻可能對您有所幫助。 將視頻文件添加到項目中時,請確保在文件檢查器中選擇了“目標”復選框。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
if let path = Bundle.main.path(forResource: "video_1523966087401 (1)", ofType: ".mp4"){
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player.play()
}
}else{
//show dialog to user
print("Error: File not found")
}
}
!
表示崩潰運算符,它解開了可選值。 比如說,那里的價值就像Optional(53)一樣。 因此,當path!
時,變量應包含nil以外的值path!
嘗試解開可選內容並在路徑變量中附加值53。
為了解決這個問題,我們可以使用兩種方法
使用警衛
guard let pathValue = path else {
return
}
let baseURL = NSURL(fileURLWithPath: pathValue) //no need to use pathValue, if you use then you have to use path!, although it makes no crash now.
AudioServicesCreateSystemSoundID(baseURL, &soundID)
//play
AudioServicesPlaySystemSound(soundID)
如果path為nil,則進入該塊並返回;如果它具有value,則繼續到下一行。
使用if-let,了解optional binding
if let pathValue = path {
let baseURL = NSURL(fileURLWithPath: pathValue) //same comment
AudioServicesCreateSystemSoundID(baseURL, &soundID)
//play
AudioServicesPlaySystemSound(soundID)
}
現在,如果path是可選的,則無法到達塊並傳遞到下一行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.