将文件存储在 Swift 2+ 来自 URLSession
Storing a file in Swift 2+ from URLSession
我正在下载一个大文件,当它完成时
URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
方法被调用。
我想将生成的文件保存在本地,例如 NSSearchPathDirectory.DocumentDirectory
。
但是我遇到了一些问题,主要是因为文件很大 500MB+
我试过:
NSFileManager.defaultManager().createFileAtPath(savePath,
contents: fileData,
attributes: nil)
对于 < 100MB 的小文件效果很好,但较大的文件会因
而死
Code=12 "Cannot allocate memory"
尝试将下载的文件转换为 NSData 时:
let data: NSData = try NSData(contentsOfURL: location,
options: NSDataReadingOptions.DataReadingMappedIfSafe)
问题是,是否有另一种方法可以将 location: NSURL
转换为 NSData
,这样大文件就不会出现内存问题?
或者有没有比 NSFileManager.defaultManager().createFileAtPath()
更好的方法来保存大文件,这样它就不需要 NSData
?
尝试使用 NSFileManager
的 copyItemAtURL:toURL:error: 将文件从某个位置复制到您想要的任何位置
我正在下载一个大文件,当它完成时
URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
方法被调用。
我想将生成的文件保存在本地,例如 NSSearchPathDirectory.DocumentDirectory
。
但是我遇到了一些问题,主要是因为文件很大 500MB+
我试过:
NSFileManager.defaultManager().createFileAtPath(savePath,
contents: fileData,
attributes: nil)
对于 < 100MB 的小文件效果很好,但较大的文件会因
而死Code=12 "Cannot allocate memory"
尝试将下载的文件转换为 NSData 时:
let data: NSData = try NSData(contentsOfURL: location,
options: NSDataReadingOptions.DataReadingMappedIfSafe)
问题是,是否有另一种方法可以将 location: NSURL
转换为 NSData
,这样大文件就不会出现内存问题?
或者有没有比 NSFileManager.defaultManager().createFileAtPath()
更好的方法来保存大文件,这样它就不需要 NSData
?
尝试使用 NSFileManager
的 copyItemAtURL:toURL:error: 将文件从某个位置复制到您想要的任何位置