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

2020-01-15 16:13:23王振洲

      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 共享文件的实例代码,有需要的朋友可以参考下。


注:相关教程知识阅读请移步到IOS开发频道。