下面的片段用于将视频保存在文档目录中(NSdata从AVCaptureMoviefileOutput接收)
func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
delegate?.recordingStopped?()
var data = NSData(contentsOfURL: outputFileURL)
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory:AnyObject=paths[0]
let dataPath=documentsDirectory.stringByAppendingPathComponent("/MyFolder")
if (!NSFileManager.defaultManager().fileExistsAtPath(dataPath)) {
NSFileManager.defaultManager() .createDirectoryAtPath(dataPath as String, withIntermediateDirectories: false, attributes: nil, error: nil)
}
var outputPathr = "\(dataPath)/TestproximityRwqxq.mp4"
var success = data!.writeToFile(outputPathr as String, options: nil, error: nil)
}如果用于其他视频(从NSbundle中选择视频并转换为NSdata),则在模拟器中使用相同的代码,但不使用设备,请帮助
发布于 2015-08-11 14:08:01
这个代码工作得很好,我们需要使用最低iOS版本8.4(XCode 6.4)的设备。版本低于8.4的设备不使用Swift2获取文档目录的内容。
发布于 2019-10-21 11:22:45
上面的解决方案,我已经修改为swift5,它是为我工作。
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
if (error != nil) {
print("Error recording movie: \(error!.localizedDescription)")
} else {
if let data = NSData(contentsOf: outputFileURL) {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths[0]
let docURL = URL(string: documentDirectory)!
let dataPath = docURL.appendingPathComponent("/DIRECTORY_NAME")
if !FileManager.default.fileExists(atPath: dataPath.absoluteString) {
do {
try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
self.directoryURL = dataPath
print("Directory created successfully-\(dataPath.path)")
} catch let error as NSError{
print("error creating directory -\(error.localizedDescription)");
}
}
let outputPath = "\(dataPath.path)/filename.mp4"
let success = data.write(toFile: outputPath, atomically: true)
// saving video into photos album.
UISaveVideoAtPathToSavedPhotosAlbum(outputPath, nil, nil, nil)
}
}
}https://stackoverflow.com/questions/31936811
复制相似问题