首页 > 解决方案 > 将大视频文件路径转换为 ​​NSData 时出现内存问题。如何使用 InputStream/FileHandle 来解决这个问题?

问题描述

我的文档目录中保存了一个大型视频。我想检索这个视频并删除它的前 5 个字节。对于超过 300 MB 的大型视频文件,使用 [NSData(contentsOf: videoURL)] 会导致内存问题错误。

我通过Swift:Loading a large video file (over 700MB) into memory 发现我们需要使用 [InputStream] 和 [OutputStream] 或 [NSFileHandle] 处理大文件。如何使用它?

示例代码如下:

   let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
   let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
   let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
   if let dirPath = paths.first{
      let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(filePath)
          do {
                let videoData = try NSData(contentsOf: videoURL)
                let mutabledata = videoData.mutableCopy() as! NSMutableData
                mutabledata.replaceBytes(in: NSRange(location: 0, length: 5), withBytes: nil, length: 0)
   }catch {
       print("Error Writing video: \(error)")
   }

标签: iosswiftnsinputstreamnsfilehandlensoutputstream

解决方案


这适用于我更改前 4 个字节,并且我没有收到弃用警告。

let input = FileHandle(forWritingAtPath: "/tmp/test.in")!
input.write("12345".data(using: .utf8)!)

推荐阅读