ios - 将大视频文件路径转换为 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)")
}
解决方案
这适用于我更改前 4 个字节,并且我没有收到弃用警告。
let input = FileHandle(forWritingAtPath: "/tmp/test.in")!
input.write("12345".data(using: .utf8)!)
推荐阅读
- go - 在运行时使用字符串/变量访问常量
- python - 将 API REST 实施到现有的 Django 应用程序
- laravel - 了解 Laravel 迁移 - 是否需要创建迁移文件
- c# - 比较列表中的单个元素
到另一个列表 - firefox - Firefox 使用本机 user_pref 将可访问的 IP 地址列入白名单(不使用扩展名)
- angular - 在 Angular 的延迟加载模块中显示组件时出错
- c++ - 为什么在尝试使 i = i*i 时出现错误“使用未初始化的内存 'i'”和“使用了未初始化的局部变量 'i'”
- customization - 在 Acuamtica 升级后,通过客户休息时的事件处理程序更新位置上的自定义字段
- java - 第二次重新调用相同方法后出现 NullPointerException
- php - 如何在已编译的 php 上配置 mysqli?- 使用 aws lambda php 脚本教程编译