3

I'm having memory leaks in my network calls for URLSession.shared in swift 3. Is this a bug or I am doing something wrong?

override func viewDidLoad() {
    super.viewDidLoad()
    let urlStr = "https://qrng.anu.edu.au/API/jsonI.php?length=10&type=hex16&size=2"
    URLSession.shared.dataTask(with: URL(string: urlStr)!) { data, response, error in
        self.view.backgroundColor = UIColor.red
        print(response)
    }.resume()
}

enter image description here

John
  • 411
  • 2
  • 8
  • 22

1 Answers1

1

Shared URL session has a credential storage for cookies and other "browser" stuff. Since it's shared it is a singleton which will live forever in your application. Instruments interprets this as a leak.

Advice: repeat the action several times before you look for leaks.

Also, quite likely the self reference in your callback holds onto your view controller while your request is still pending. Use weak self at the block start to break the cycle. But that totally depends on your design. It got me at least in a few cases.

I also want to refer to this answer: https://stackoverflow.com/a/35757989/3351794

Community
  • 1
  • 1
Andreas Pardeike
  • 4,622
  • 1
  • 17
  • 27
  • Is there any other way for network calls that wont cause a memory leak? Cause I've tried a couple of ways such as creating a new `URLSession`, using `ephimeral` which according to [this](http://footle.org/2015/10/10/fixing-a-swift-memory-leak/) works. But so far with no success – John Mar 14 '17 at 08:24
  • Network calls via the latest URLSession do not leak memory. So I don't understand your question. I use it in my own app without any problems. Please see eskimos answer here: https://forums.developer.apple.com/thread/14785 – Andreas Pardeike Mar 14 '17 at 08:37
  • So you mean that the "leak" detected by instruments is not actually a leak? – John Mar 15 '17 at 01:06
  • 1
    Yes. A leak is an allocation that does not go away. So let's say you have code that loops through something and inside there you use a singleton. The first iteration will create the singleton and all other iterations use it only (no more allocation). Since the singleton is never released, do you count it as a leak? No. You would only count leaks if you do an operation repeatedly and the memory consumption increases all the time. Also, have a look at this discussion about the side effects of UrlSessions: http://stackoverflow.com/a/35757989/3351794 – Andreas Pardeike Mar 15 '17 at 06:24
  • Well that clarifies everything. Thanks. – John Mar 15 '17 at 06:59