我正在尝试从中读取.mid文件DocumentDirectory.我试过这个:
var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
var midiFileURL = NSURL.fileURLWithPath(path)
Run Code Online (Sandbox Code Playgroud)
问题是:
从'String?'垮掉 'String'只展开选项; 你的意思是用'!'?
一旦我从DocumentsDirectory我想要的文件中读取文件就可以了:
guard let bankURL = NSBundle.mainBundle().URLForResource("gs_instruments", withExtension: "dls") else {
fatalError("\"gs_instruments.dls\" file not found.")
}
do {
try self.midiPlayer = AVMIDIPlayer(contentsOfURL: midiFileURL, soundBankURL: bankURL)
print("created midi player with sound bank url \(bankURL)")
} catch let error as NSError {
print("Error \(error.localizedDescription)")
}
self.midiPlayer.prepareToPlay()
self.midiPlayer.play({
print("midi done")
})
Run Code Online (Sandbox Code Playgroud)
我该如何修复错误?非常感谢.
NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first回来了Optional<String>(又名String?).你试图把它投射到String.警告告诉你,你是以一种繁琐的方式做到这一点.您可以强行打开它!:
var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
Run Code Online (Sandbox Code Playgroud)
当然,因为你是强制解包,所以如果返回的值是nil(在没有first... 的情况下,当集合为空时),你的应用程序可能会崩溃.
我强烈建议您阅读Swift语言指南 - 基础知识中的Optionals .