Swift 4 – 檢查檔案是否存在

// let resourcePath: String = Bundle.main.resourcePath! + "/\(mySongName)"
                let mySongNameArr = mySongName.split(separator: ".")
                let resourcePath = Bundle.main.path(forResource: String(mySongNameArr[0]), ofType: String(mySongNameArr[1]))!
                
                currentSong = mySongName
                player = nil
                
                let fileManager = FileManager.default
                if fileManager.fileExists(atPath: resourcePath) {
                    print("FILE AVAILABLE")
                    do {
                        try player = AVAudioPlayer.init(contentsOf: URL.init(string: resourcePath)!)
                    } catch let error as NSError {
                        print(error)
                    }
                } else {
                    print("FILE NOT AVAILABLE")
                }

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.