我在 xcode 8.2 中将 swift 2.3 转换为 swift 3
swift 2.3:有代码,有代码,有代码,有代码,有代码
func playAudio() {
self.stopAudio()
let lessonObject:LessonObject = self.lessonArray[self.selectedIndex] as! LessonObject
let fullPath:String! = Constants.URL_HOST + "\(lessonObject.lessonPath)"
let soundURL:NSURL! = NSURL.init(string:fullPath)
let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let destinationUrl = documentsDirectoryURL.URLByAppendingPathComponent(soundURL.lastPathComponent!)
if NSFileManager().fileExistsAtPath(destinationUrl!.path!) {
if let soundData = NSData(contentsOfFile: destinationUrl!.path!) {
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
return
}
if let soundData = NSData(contentsOfURL:NSURL(string:fullPath)!) {
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
}
swift 3:代码有错误吗?
func playAudio() {
self.stopAudio()
let lessonObject:LessonObject = self.lessonArray[self.selectedIndex] as! LessonObject
let fullPath:String! = Constants.URL_HOST + "\(lessonObject.lessonPath)"
let soundURL:URL! = URL.init(fileURLWithPath: fullPath)
let documentsDirectoryURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent(soundURL.lastPathComponent)
if FileManager().fileExists(atPath: destinationUrl.path){
if let soundData = try? Data(contentsOf: URL(fileURLWithPath: destinationUrl.path))
{
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
return
}
if let soundData = try? Data(contentsOf: URL(string:fullPath)!)
{
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
}
转换我的错误后:
在展开 Optional 值时发现 nil。
我构建了 swift 2.3:destinationUrl = "file:///Users/admin/Library/.../Documents/test.mp3" 0x00006080002a73e0
我构建了 swift 3:destinationUrl = "file:///Users/admin/Library/.../Documents/Optional(%22test.mp3%22)"