Beginning Networking with URLSession

Sep 13 2022 · Swift 5.6, iOS 15, Xcode 13.4.1

Part 1: Introduction to URLSession & Concurrency

02. Introduction to Modern Concurrency

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 01. Introduction Next episode: 03. More Modern Concurrency

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 02. Introduction to Modern Concurrency

Concurrency - The Swift Programming Language

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

URLSession is designed to access networks beyond your user’s device. Doing so takes time; whether to upload data or respond to a chat message. That’s time the user can be doing other things.

Task {
  print("Doing some work on a task.")
}

print("Doing work on the main actor (main thread).")
Task {
  print("This is first.")
    
  let sum = (1...100000).reduce(0, +)
  print("This is second: 1 + 2 + 3 ... 100 = \(sum)")
}

print("This is last.")
let task = Task {
  print("This is first.")
    
  let sum = (1...100000).reduce(0, +)
  try Task.checkCancellation()
  print("This is second: 1 + 2 + 3 ... 100 = \(sum)")
}

print("This is last.")
task.cancel()
Task {
  print("Starting the task.")
  try await Task.sleep(nanoseconds: 1_000_000_000)
  print("Finishing the task.")
}
func performTask() {
  print("Starting the task in a function.")
  try await Task.sleep(nanoseconds: 1_000_000_000)
  print("Finishing the task in a function.")
}
func performTask() throws {
func performTask() async throws {
Task {
  try await performTask()
}
func fetchDomains() async throws -> [Domain] {
  []
}
func fetchDomains() async throws -> [Domain] {
  let url = URL(string: "https://api.raywenderlich.com/api/domains")!
  let (data, _) = try await URLSession.shared.data(from: url)
    
  return try JSONDecoder().decode(Domains.self, from: data).data
}
Task {
  do {
    let domains = try await fetchDomains()
    for (index, domain) in domains.enumerated() {
      let attr = domain.attributes
      print("\(index + 1)) \(attr.name): \(attr.description) - \(attr.level)")
    }
  } catch {
    print(error)
  }
}