Summary of Swift Shared File Operations (iOS 8 +)

  • 2020-06-15 10:20:53
  • OfStack

preface

For iOS 8 + local Shared file list

The body of the

1. Prepare

1.1 By default, App's file sharing is turned off. It needs to be enabled in plist:

Application supports iTunes file sharing is set to YES

QiYongHouBaSheBeiLianJieDao iTunes 上,在 iTunes YingYongLiDeWenJianGongXiangJiuNengKanDaoNiDe App 了(如果看不见需要断开重新拔插1下数据线),可以拷贝1些视频进去,便于测试。

1.2 the import library

Photos. framework

AVKit.framework for playing videos

2. 获取视频列表


 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)
    }
  }

Code description:

Note the use of swift, such as fileExistsAtPath

b) and String's pathExtension and lastPathComponent are gone. They have been changed to NSURL. Many online materials still take these attributes from NSString or String

The duration of the video can be obtained by CMTimeGetSeconds(AVURLAsset(URL: ES62en.url, options: nil).duration)

3. Play the video


 func play(file: File) {
    let player = AVPlayer(URL: file.url)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.presentViewController(playerViewController, animated: true) {
      playerViewController.player?.play()
    }
  }

4. With... Open the


 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)
  }

Delete the video


 func delete(file: File, indexPath: NSIndexPath) {
    do {
      try fileManager.removeItemAtPath(file.path)
      videos.removeAtIndex(indexPath.row)
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    } catch {
      
    }
  }

6. Save to album


 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
    }
  }

Code description:

Note the use of UISaveVideoAtPathToSavedPhotosAlbum, after which Selector will report an error if written incorrectly.

Above is the IOS 8 Shared file example code, friends in need can refer to below.


Related articles: