简体   繁体   English

xcode9 swift4致命错误:展开一个可选值时意外发现nil

[英]xcode9 swift4 Fatal error: Unexpectedly found nil while unwrapping an Optional value

I am trying to play a mp3 file(5 seconds) when app launched and I keep getting the error: 应用启动时,我试图播放mp3文件(5秒),但不断出现错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value 线程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.
    }

}

Can anyone explain why and how I can fix this? 谁能解释为什么以及如何解决这个问题?

Check these points, all conditions must be true: 检查以下几点,所有条件都必须为真:

  • Is the file in the project navigator? 该文件是否在项目导航器中?
  • Is the Target Membership checkbox checked in the File Inspector (to get it select the file and press ⌥⌘1 ) 在文件检查器中是否选中了“ Target Membership复选框(要获取它,请选择文件并按⌥⌘1
  • Is the file name spelled correctly ( iPhone100Voice.mp3 )? 文件名的拼写是否正确( iPhone100Voice.mp3 )?

Please check your file name, maybe filename is incorrect or not in the bundle 请检查您的文件名,也许文件名不正确或捆绑包中没有

So please check file name with extension. 因此,请检查带有扩展名的文件名。

Use if let or guard to unwrap the path: if letguard 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)

   }
}

It may be help's to you to play video. 播放视频可能对您有所帮助。 While adding video file into project make sure target checkbox selected or not in file inspector. 将视频文件添加到项目中时,请确保在文件检查器中选择了“目标”复选框。

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")
        }
    }

! means crash operator, it unwraps optional value. 表示崩溃运算符,它解开了可选值。 Value there works as like Optional(53) , for say. 比如说,那里的价值就像Optional(53)一样。 So the variable should contain value except nil, when path! 因此,当path!时,变量应包含nil以外的值path! tries to unwrap optional and appends value 53 in path variable. 尝试解开可选内容并在路径变量中附加值53。

to fix this we can use two ways 为了解决这个问题,我们可以使用两种方法

Using guard, 使用警卫

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)

if path is nil, it enters the block and return , if it has value , it continues to next line. 如果path为nil,则进入该块并返回;如果它具有value,则继续到下一行。

using if-let, knowing optional binding 使用if-let,了解optional binding

if let pathValue = path {
    let baseURL = NSURL(fileURLWithPath: pathValue) //same comment
    AudioServicesCreateSystemSoundID(baseURL, &soundID)
    //play
    AudioServicesPlaySystemSound(soundID)
} 

Now, if path is optional , can't reach the block and pass to next line 现在,如果path是可选的,则无法到达块并传递到下一行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift:致命错误:在展开可选值时意外发现nil - Swift : fatal error: unexpectedly found nil while unwrapping an Optional value Xcode Swift:appDelgate.window! is nil :致命错误:在解开可选值时意外发现 nil - Xcode Swift : appDelgate.window! is nil : Fatal error: Unexpectedly found nil while unwrapping an Optional value 快速致命错误:解开Optional值时意外发现nil - swift fatal error: unexpectedly found nil while unwrapping an Optional value Swift致命错误:解开Optional值时意外发现nil - Swift fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:在Swift 3中解开Optional值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value in Swift 3 SWIFT-致命错误:解开可选值时意外发现nil - SWIFT - fatal error: unexpectedly found nil while unwrapping an Optional value Swift4:FMDBdatabase-展开一个可选值时意外地找到nil - Swift4 : FMDBdatabase - Unexpectedly found nil while unwrapping an Optional value 展开一个Optional值时意外发现nil? 迅捷4 - Unexpectedly found nil while unwrapping an Optional value? Swift4 Xcode控制台错误消息:“致命错误:在展开可选值时意外发现nil”(快速) - Xcode console error message: 'fatal error: unexpectedly found nil while unwrapping an Optional value' (Swift) Swift-致命错误:解开Optional值时意外发现nil - Swift - Fatal error: unexpectedly found nil while unwrapping an Optional values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM