1. 程式人生 > >【Swift 2.1】共享檔案操作小結(iOS 8 +)

【Swift 2.1】共享檔案操作小結(iOS 8 +)

前言

  適用於 iOS 8 + 本地共享檔案列表

宣告
  歡迎轉載,但請保留文章原始出處:)
  部落格園:http://www.cnblogs.com
  農民伯伯: http://over140.cnblogs.com

正文 

  一、準備

    1.1  預設 App 的檔案共享是關閉的,需要在 plist 中設定啟用:

    Application supports iTunes file sharing  設定為  YES

      啟用後把裝置連線到 iTunes 上,在 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 的用法

      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 寫得不對就會報錯。

結束

  一口氣寫完一個功能好爽