I'm trying to load a large video file (over 700MB) into memory from the documents directory using let data: NSData = NSFileManager.defaultManager().contentsAtPath(path)!
but it crashes my app. Smaller files load fine. Is there a better way to load larger files? Thanks.
Asked
Active
Viewed 2,075 times
0

Chris
- 11
- 2
-
1Why are you trying to load such a large file into memory all at once? What are you going to do with the data? – rmaddy Mar 23 '16 at 21:57
-
Try http://stackoverflow.com/questions/31181322/upload-large-video-via-nsurlsession-causes-memory-pressure-crash and delete this question if it's a dup. – BaseZen Mar 23 '16 at 21:59
-
Thanks BaseZen, I'll check it out. Maddy, after loading the file i chunk it up using data.subdataWithRange(range) and upload it to Dropbox. – Chris Mar 23 '16 at 22:29
-
Use an `NSFileHandle` to read the file in chunks. – rmaddy Mar 23 '16 at 22:36
-
You should not be doing that. If you need to read frames from video, that can be done with AVAssets to decode the data. But, 700 megs is too large to memory map into an iOS app, it will crash you app every time. – MoDJ Mar 23 '16 at 23:06
-
Short answer: You can't. What are you trying to do? If you want to play the video, you should use one of the built-in frameworks for playing video. If you want to copy the file you should use NSFileManager or other file system APIs that will copy the file in blocks. – Duncan C Mar 23 '16 at 23:58
-
Thanks rmaddy, NSFileHandle was what I needed. – Chris Mar 24 '16 at 01:18
1 Answers
5
Depending on what you want to do with the file, using NSData.init(contentsOfURL:options:)
with the option .DataReadingMappedIfSafe
may work for you.
This will map the file into memory (if possible), i.e. the file's contents will only be loaded (page by page) as you access them via the bytes
property.

Ole Begemann
- 135,006
- 31
- 278
- 256