本文記錄一個適用於 iOS 8 以上的本地共享文件列表實作:從 Documents 目錄掃描多媒體檔案,支持播放、用其他應用打開、刪除與存入相簿。
1.1 開啟文件共享
App 的文件共享預設是關閉的,需要在 plist 中把 Application supports iTunes file sharing 設為 YES。啟用後把設備連上 iTunes,在應用列表的「文件共享」裡就能看到你的 App(若沒出現,拔插一次數據線即可)。可以丟幾個影片進去方便測試。
1.2 引入框架
Photos.framework、AVKit.framework(用於播放影片)。
private let VIDEO_EXTENSIONS = [ ".MOV", ".MP4" ] private var fileManager = NSFileManager.defaultManager() func loadVideos() { var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) if paths.count > 0 { let documentsDirectory = paths[0] as String let documentUrl = NSURL(fileURLWithPath: documentsDirectory, isDirectory: true) do { documentUrl.path let files = try fileManager.contentsOfDirectoryAtPath(documentsDirectory) for file in files { fetchVideos(documentUrl.URLByAppendingPathComponent(file).path ?? "") } } catch { } self.tableView.reloadData() } } func fetchVideos(path: String) { var isDir: ObjCBool = false if !path.isEmpty && fileManager.fileExistsAtPath(path, isDirectory: &isDir) { if isDir { do { let files = try fileManager.contentsOfDirectoryAtPath(path) for file in files { fetchVideos(file) } } catch { } } else { var file = File(path: path) if file.isValid() && isVideoFileExtension(file.fileExtension.uppercaseString) { do { if let attr: NSDictionary = try fileManager.attributesOfItemAtPath(path) { file.fileSize = attr.fileSize() } } catch { } videos.append(file) } } } } func isVideoFileExtension(ext: String) -> Bool { for videoExtension in VIDEO_EXTENSIONS { if ext == videoExtension { return true } } return false } struct File { var fileExtension = "" var fileName = "" var path = "" var assert: AVURLAsset? var url: NSURL! var fileSize: UInt64 = 0 init(path: String) { self.path = path self.url = NSURL(fileURLWithPath: path) self.fileName = url.lastPathComponent ?? "" self.fileExtension = "." + (url.pathExtension ?? "") } func isValid() -> Bool { return !(fileName.isEmpty || fileExtension.isEmpty) } }
a) 注意 Swift 中 fileExistsAtPath 的用法帶有 inout 參數。
b) String 的 pathExtension 與 lastPathComponent 已被移除,統一改到 NSURL 下。網上很多舊資料還在從 NSString/String 取這兩個屬性,照抄會編譯失敗。
c) 影片時長可以透過 AVURLAsset 取得:CMTimeGetSeconds(AVURLAsset(URL: file.url, options: nil).duration)。
func play(file: File) { let player = AVPlayer(URL: file.url) let playerViewController = AVPlayerViewController() playerViewController.player = player self.presentViewController(playerViewController, animated: true) { playerViewController.player?.play() } }
func openIn(file: File, indexPath: NSIndexPath) { let document = UIDocumentInteractionController(URL: file.url) let rect = self.tableView.rectForRowAtIndexPath(indexPath) document.presentOpenInMenuFromRect(rect, inView: self.tableView, animated: true) }
func delete(file: File, indexPath: NSIndexPath) { do { try fileManager.removeItemAtPath(file.path) videos.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } catch { } }
func saveToCameraRoll(file: File, indexPath: NSIndexPath) { if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file.path) { UISaveVideoAtPathToSavedPhotosAlbum(file.path, self, "image:didFinishSavingWithError:contextInfo:", nil) } else { // save faild } } func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) { if error == nil { // save success } else { // save faild } }
這裡最容易出錯的是 UISaveVideoAtPathToSavedPhotosAlbum 的最後一個 Selector 參數,字串寫錯一個字元就會在執行期崩潰,而且編譯器完全不報警。建議把回調方法名抽成常數再引用。