Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 URLSession memory leak

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

like image 532
John Avatar asked Mar 22 '26 15:03

John


1 Answers

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

like image 126
Andreas Pardeike Avatar answered Mar 24 '26 03:03

Andreas Pardeike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!