你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> Swift 共享文件操作小結(iOS 8 +)

Swift 共享文件操作小結(iOS 8 +)

編輯:IOS開發綜合

前言

  適用於 iOS 8 + 本地共享文件列表

正文

  一、准備

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

以上就是IOS 8 共享文件的實例代碼,有需要的朋友可以參考下。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved