HTTP requests leak memory and cause app or even device to crash
My app sometimes needs to download large amounts of data (100MB+). I can't do it in a single go because Ti's HTTP request is memory-backed. So instead I chunk the file on the server side, download a bunch of files, and stitch them back up.
Unfortunately, this only delays the problem - after fetching about 100MB of 8-9MB files, my iPod 2nd gen freezes and reboots itself. A number of my users have reported similar experiences.
So I spent some time digging through the code. I could count my number of hours of objc experience on one hand, so this needs to be taken with a grain of salt. But here's what I found.
Profiling the code with xcode's instruments reveals that ASIHTTPRequest's rawResponseData variable, among other things, is not being freed. It is set to autorelease, but evidently it is not being done. Cursory googling reveals that autorelease is unreliable on the iPhone - perhaps Ti has to be doing something to free the autoreleasepool?
The following patch halts the memory leak I was experiencing. I'm not sure if keep-alive connections are no longer available with this fix, but I'd much rather my app doesn't crash. If anyone has a more elegant way of fixing this, I'd love to hear about it.
http://github.com/dae/titanium_mobile/commit/346021b383b87257a84bc648c4cefa98d503620b
3 Answers
-
Used Demien suggestion.
Set the file property for the HTTP client, so the request is saved directly to a file instead of being maintained in the buffer. Memory use drastically reduced.
Thanks!! -
I'm having a similar issue, and I can't really chunk the files since they are not on my server. Were you able to get a more reliable response or fix for this problem?
Thanks!
-
The problem is that ti downloads the whole file and then proceeds to save the content to the file. Obviously if the file is larger than the avb mem, its going to crash and some cases restart the device. To handle this, I wrote a module in objc that saves the content as its downloaded and at the same time frees the resource. This has worked very well for me, I been able to download over 2 GB file and only 10 mb usage increase (might be due to other components of Ti).
Would you guys be interested in such module?