Group Group Group Group Group Group Group Group Group

URLSession Tutorial: Getting Started | raywenderlich.com

#1

In this URLSession tutorial, you’ll learn how to create HTTP requests as well as implement background downloads that can be both paused and resumed.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3244963-urlsession-tutorial-getting-started
#2

Hello @Audrey, @kentoh, can you explain the use of [weak var] in the code snippet below? Why is weak self needed at all? If it is definitely needed to not get into a strong reference cycle, would unowned not be better?

Thanks in advance!
Chris

// 4
if let index = download?.track.index {
  DispatchQueue.main.async { [weak self] in
    self?.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], 
                               with: .none)
  }
}
#3

Hi Christopher, it’s in our Swift style guide: https://github.com/raywenderlich/swift-style-guide#extending-lifetime

But there should also be this guard statement to avoid optional chaining:

 guard let self = self else {
    return
  }
#4

Hi @audrey, thanks for the quick reply and link. I still don’t understand where the need of [weak self] arises as I cannot see where the strong reference in this closure is located. The closure itself is not referenced as a property of the class itself, which I understood from Apple’s Swift programming guide to be the reason for strong references in closures.

#5

I found this explanation: it seems it’s more a case of not reloading the row if the view controller has been released.

actually, Felipe / @airjordan12345 added that weak self so he’ll be able to explain it better :wink: