在 Swift 中将视频保存在本地(目录)中?
Posted
技术标签:
【中文标题】在 Swift 中将视频保存在本地(目录)中?【英文标题】:Saving video in locally (directory) in Swift? 【发布时间】:2020-10-16 21:18:15 【问题描述】:我尝试在本地保存给定的视频,然后我需要这些保存的视频在我的应用中播放视频。我无法处理保存的视频。这是我的保存尝试:
func saveVideoDocumentDirectory(url : URL)
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(".MOV")
do
let videoData = try Data(contentsOf: url)
fileManager.createFile(atPath: paths as String, contents: videoData, attributes: nil)
catch
//
这里是get文件试试
func getVideo()
let fileManager = FileManager.default
let videoPAth = (self.getDirectoryPath() as NSString).appendingPathComponent(".MOV")
if fileManager.fileExists(atPath: videoPAth)
print(videoPAth)
play(url: URL(string: videoPAth)!)
else
print("No Video")
这是我的播放视频功能:
func play(url : URL)
let player = AVPlayer(url: url)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
present(playerViewController, animated: true)
playerViewController.player!.play()
【问题讨论】:
【参考方案1】:请尝试使用write
,而不是Filemanager.createFile()
。
let videoData = try Data(contentsOf: url)
try videoData.write(to: paths, options: .atomic)
另外,我建议先创建一个文件夹(来自 answer)。
extension URL
static func createFolder(folderName: String) -> URL?
let fileManager = FileManager.default
// Get document directory for device, this should succeed
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first
// Construct a URL with desired folder name
let folderURL = documentDirectory.appendingPathComponent(folderName)
// If folder URL does not exist, create it
if !fileManager.fileExists(atPath: folderURL.path)
do
// Attempt to create folder
try fileManager.createDirectory(atPath: folderURL.path,
withIntermediateDirectories: true,
attributes: nil)
catch
// Creation failed. Print error & return nil
print(error.localizedDescription)
return nil
// Folder either exists, or was created. Return URL
return folderURL
// Will only be called if document directory not found
return nil
然后,你可以这样保存:
guard let folderURL = URL.createFolder(folderName: "StoredVideos") else
print("Can't create url")
return
let permanentFileURL = folderURL.appendingPathComponent(nameOfYourFile).appendingPathExtension("MOV")
let videoData = try Data(contentsOf: url)
try videoData.write(to: permanentFileURL, options: .atomic)
这将为您省去NSSearchPathForDirectoriesInDomains
的麻烦。
【讨论】:
以上是关于在 Swift 中将视频保存在本地(目录)中?的主要内容,如果未能解决你的问题,请参考以下文章
在 Swift 中将 UIView 保存和检索为 NSData
如何在 Swift 中归档和取消归档自定义对象?或者如何在 Swift 中将自定义对象保存到 NSUserDefaults?