Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Created December 7, 2016 17:07
Show Gist options
  • Save ricardopereira/5904536bbfb87e3a457a022b2bfa8f79 to your computer and use it in GitHub Desktop.
Save ricardopereira/5904536bbfb87e3a457a022b2bfa8f79 to your computer and use it in GitHub Desktop.
The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you do not invalidate the session, your app leaks memory until it exits.
import UIKit
class ModalViewController: UIViewController, NSURLSessionDelegate {
var session: NSURLSession!
override func viewDidLoad() {
super.viewDidLoad()
session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), delegate: self, delegateQueue: nil)
dispatch_async(dispatch_get_main_queue()) { [weak self] in
for i in 0...100 {
self?.session.dataTaskWithRequest(NSURLRequest(URL: NSURL(string: "https://google.pt")!), completionHandler: { data, response, error in
print("session.dataTaskWithRequest \(i): done")
}).resume()
}
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
// Comment the line after to check that the view controller isn't released.
session.finishTasksAndInvalidate()
}
@IBAction func didTouchClose(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
deinit {
print("ViewController.deinit")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment