我用于在文档目录中保存视频的片段(从AVCaptureMoviefileOutput收到的NSdata)
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),相同的代码在模拟器中工作,但不能使用设备,请帮助
答案 0 :(得分:0)
此代码工作正常,我们需要使用最低iOS版本为8.4(XCode 6.4)的设备。版本低于8.4的设备没有使用Swift2获取文档目录的内容。
答案 1 :(得分:0)
我为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)
}
}
}