Search code examples
iosswiftmemory-leaksnsurlcache

CFURLCacheNode leaks in swift?


I am using alamofire for networking. When I download files from the server CFURLCachNode leaks occur.

I have tried all the solutions i could find.

I have created sharedUrlCache

let URLCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
    NSURLCache.setSharedURLCache(URLCache)

Also i removed the cache in didRecieveMemoryWarning(). After all that I still get the leaks.

The snapshot is included below: enter image description here

How can I get rid of this?


Solution

  • Ok let me get this straight. Your question is unclear as you didn't mention how you are creating the request. Anyway let me assume it for you.

    The reason I could find is , if there is no file in the server ie.,404 error , its possible to get the leaks. If you fix that you wont get it.

    You can follow the below code to avoid such errors in future even if the file is missing.

    var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: serverFileURL)!)
    mutableURLRequest.HTTPShouldHandleCookies = false
    mutableURLRequest.HTTPShouldUsePipelining = true
    mutableURLRequest.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad //You can find the details in Apple Documentation
    
    //Replace your request with the mutableURLRequest
    

    Hope this solution works for your situation. Let me know if you find any issues.