Intro to iOS Development
  • Welcome
    • β˜€οΈIntroduction
    • 🐣Getting Started
    • 🐦Course Staff
  • Logistics
    • πŸ“œSyllabus
    • πŸ—“οΈSchedule
    • πŸ–ŠοΈGrading
    • πŸ™‹β€β™‚οΈOffice Hours
    • Ed Discussion
  • Assignments
    • 🍼A1: Swift Basics
    • πŸ§‘A2: Profile
    • πŸ’¬A3: ChatDev
    • πŸ‘¨β€πŸ³A4: ChefOS
    • πŸ‘¨β€πŸ³A4: ChefOS - SwiftUI
    • πŸ“±Hack Challenge
      • πŸ†FA23 Winners
  • Lectures
    • 1️⃣Logistics + Swift Basics
    • 2️⃣UIKit + AutoLayout
  • 3️⃣MVC + Navigation + Delegation
  • 4️⃣UITableView
  • 5️⃣UICollectionView
  • 6️⃣Networking I
  • 7️⃣Networking II
  • 8️⃣SwiftUI I
  • 9️⃣SwiftUI II
  • πŸ”ŸPersistence + SnapKit
  • πŸ””(11) Notifications
  • 🌎(12) Deployment and MapKit
  • Chapters
    • πŸ–οΈIntroduction
    • ☁️Git + GitHub
      • 1️⃣Git Installation
      • 2️⃣Git Basics
      • βž•Git+
    • 🐣Swift Basics
      • 1️⃣Variables and Constants
      • 2️⃣Data Types
      • 3️⃣Operators
      • 4️⃣Data Structures
      • 5️⃣Conditionals
      • 6️⃣Loops
      • 7️⃣Functions
      • 8️⃣Closures
      • 9️⃣Optionals
    • 🧰UIKit + AutoLayout
      • 1️⃣Classes
      • 2️⃣UIKit
      • 3️⃣AutoLayout
    • πŸ“ΊMVC + Navigation + Delegation
      • 1️⃣MVC
      • 2️⃣Navigation
      • 3️⃣Delegation
    • πŸ“UITableView
      • 1️⃣What is a UITableView?
      • 2️⃣UITableView Setup
    • πŸ“šUICollectionView
      • 1️⃣What is a UICollectionView?
      • 2️⃣UICollectionView Setup
    • 🌐Networking I
      • 1️⃣HTTP Requests
      • 2️⃣Callbacks
      • 3️⃣Codable
    • 🌍Networking II
      • 1️⃣Alamofire
      • 2️⃣GET Requests
      • 3️⃣POST Requests
      • 4️⃣URLSession
    • πŸ’ΎPersistence + SnapKit
      • 1️⃣Persistence
      • 2️⃣SnapKit
    • πŸ•ŠοΈSwiftUI
      • 1️⃣Introduction to SwiftUI
      • 2️⃣Getting Started with SwiftUI
      • 3️⃣Views + Modifiers
      • 4️⃣Layouts
      • 5️⃣Navigation
      • 6️⃣Property Wrappers
    • πŸŽ›οΈWidgets
      • 1️⃣Introduction to Widgets
      • 2️⃣Setting Up Widgets
      • 3️⃣Building Widgets
      • 4️⃣Configuring Widgets
    • 🧱Project Foundation
    • βœ…Testing
      • 1️⃣Unit Testing
    • πŸ‘£Debugging
      • 1️⃣OSLog
      • 2️⃣Crashlytics
      • 3️⃣Analytics
    • ☁️CI/CD
      • 1️⃣Xcode Cloud
      • 2️⃣AppStore Shipping
  • Guides
    • πŸ”¨Xcode Project Setup
    • 🎨Figma
    • πŸ“¬Postman
    • πŸ₯₯CocoaPods
    • 🧰UIKit Handbook
    • πŸ“‘Tab Views
      • UITabBarController
      • TabView
  • Work in progress
    • 🧡Concurrency
    • 2️⃣UI Testing
    • πŸ•Reactive Programming
    • 🧠Memory Management
      • πŸ”ARC
    • πŸ“¦Storage
    • πŸ“£Notifications
  • Archived
    • SP24
      • Logistics
        • πŸ“œSyllabus
        • πŸ—“οΈSchedule
        • πŸ–ŠοΈGrading
        • πŸ™‹β€β™‚οΈOffice Hours
      • Assignments
        • 🍼A1: Swift Basics
        • πŸ§‘A2: Profile
        • πŸ’¬A3: ChatDev
        • πŸ‘¨β€πŸ³A4: ChefOS
        • πŸ“±Hack Challenge
          • πŸ†FA23 Winners
      • Lecture
        • 0️⃣Course Intro + Logistics + Git Setup
        • 1️⃣Swift Basics
        • 2️⃣UIKit + AutoLayout
        • 3️⃣MVC + Navigation + Delegation
        • 4️⃣UITableView
        • 5️⃣UICollectionView
        • 6️⃣Networking I
        • 7️⃣Networking II
        • 8️⃣Persistence + SnapKit
        • πŸ”ŸSwiftUI
        • πŸ”’TabViews
    • FA23
      • Logistics
        • 🐣Getting Started
        • 🐦Course Staff
        • πŸ“œSyllabus
        • πŸ—“οΈSchedule
        • πŸ–ŠοΈGrading
        • πŸ™‹β€β™‚οΈOffice Hours
      • Assignments
        • 🍼A1: Swift Basics
        • πŸ§‘A2: Profile
        • πŸ’¬A3: ChatDev
        • πŸ‘¨β€πŸ³A4: ChefOS
        • πŸ“±Hack Challenge
          • πŸ†FA23 Winners
      • Lectures
        • 0️⃣Course Intro + Logistics
        • 1️⃣Swift Basics
        • 2️⃣UIKit + AutoLayout
        • 3️⃣MVC + Navigation + Delegation
        • 4️⃣UITableView
        • 5️⃣UICollectionView
        • 6️⃣Networking I
        • 7️⃣Networking II
        • 8️⃣Persistence + SnapKit
        • πŸŽ›οΈWidgets
          • πŸ‘ΌIntroduction to Widgets
          • βš’οΈSetting Up Widgets
          • 🧱Building Widgets
          • πŸ‘¨β€πŸ’»Configuring Widgets
        • πŸ”ŸSwiftUI
    • SP23
      • Logistics
        • Lecture Schedule
        • Syllabus
        • Grading
        • SP23 Office Hours
      • Chapters
        • 1. Intro to Swift & Xcode
          • Lecture Handout
          • Lecture Demo
          • 🍼Project: Swift Basics
        • 2. UIKit and AutoLayout
          • Lecture Handout
          • Lecture Demo
          • πŸ›’Project: UIKit + AutoLayout
        • 3. Navigation, MVC, and Delegation
          • Lecture Handout
          • Lecture Demo
          • Project: Navigation + Delegation
        • 4. UITableView
          • Lecture Handout
          • Lecture Demo
          • Project: UITableView
        • 5. UICollectionView
          • Lecture Handout
          • Lecture Demo
          • Project: UICollectionView
        • 6. Networking I
          • Lecture Handout
          • Lecture Demo
          • Project: Persistence
        • 7. Networking II
          • Lecture Handout
          • Lecture Demo
            • Message Board
          • Project: Networking II
        • 8. Swift UI
        • 9. CocoaPods
          • 🍫Lecture Handout
          • πŸ§‘β€πŸ³Lecture Demo
      • Cheat Sheets
        • Setting Up a New Xcode Project
        • Submitting Your Projects
        • Setting Up CocoaPods
    • 2022
      • SwiftUI
    • 2021
      • Adding Flare
      • Project: UIView Animations (Optional - Extra Credit)
      • UIView Animations
      • Xcode Tips and Tricks
    • 2019
      • Firebase
      • Persistence: UserDefaults
  • Swift Guide (ARCHIVED)
    • About this Textbook
    • Documentation
    • Constants and Variables
      • Variable Properties
      • Lazy and Static Variables
    • Functions
    • Ranges
    • Arrays
      • Basic Array Operations
      • Iteration and Enumeration
      • Advanced Array Operations
    • Tuples
    • Conditions and While Loops
    • For Loops
    • Enums and Switches
      • Enums with Associated Values
      • Indirect Enums
    • Classes and Structs
    • Optionals
    • Dictionaries
      • Dictionary Implementation
    • Closures
    • Constraints
    • Generics
    • Protocols
      • Protocols With Associated Types
    • Casting
    • Errors
    • Networking
      • Result
    • Inout
Powered by GitBook
On this page
  • GET Requests
  • POST Requests

Was this helpful?

Export as PDF
  1. Chapters
  2. Networking II

URLSession

Fall 2023 | Vin Bui

In the previous sections, we used Alamofire to send network requests. Although Alamofire is very elegant and simple to use, there are times when we want to use native Swift to send network requests. We can do this with URLSession.

GET Requests

Let’s take a look at the Alamofire version from the previous section:

// 1. Create the function
func fetchRoster(completion: @escaping ([Member]) -> Void) {
    // 2. Specify the endpoint
    let endpoint = "<Enter URL String Here>"
    
    // 3. Create a decoder
    let decoder = JSONDecoder()
    // decoder.dateDecodingStrategy = .iso8601 // Only if needed
    // decoder.keyDecodingStrategy = .convertFromSnakeCase // Only if needed
    
    // 4. Create the request
    AF.request(endpoint, method: .get)
        .validate()
        .responseDecodable(of: [Member].self, decoder: decoder) { response in
	    // 5. Handle the response
            switch response.result {
            case .success(let members):
                print("Successfully fetched \(members.count) members")
                completion(members)
            case .failure(let error):
                print("Error in NetworkManager.fetchRoster: \(error)")
            }
        }
}

We can do the same exact thing using URLSession (only steps after Step 3 are different):

// 1. Create the function
func fetchRoster(completion: @escaping ([Member]) -> Void) {
    // 2. Specify the endpoint
    let endpoint = "<Enter URL String Here>"
    
    // 3. Create a decoder
    let decoder = JSONDecoder()
    // decoder.dateDecodingStrategy = .iso8601 // Only if needed
    // decoder.keyDecodingStrategy = .convertFromSnakeCase // Only if needed

    // 4. Create a URLRequest
    var urlRequest = URLRequest(url: URL(string: endpoint)!)
    urlRequest.httpMethod = "GET"
    
    // 5. Create and resume the task
    URLSession.shared.dataTask(with: urlRequest) { data, response, error in
        // 6. Handle the response (you can also do something with `response`)
        guard error == nil, let data else {
            print("Error in NetworkManager.fetchRoster: \(error)")
            return
        }

        if let members = try? decoder.decode([Member].self, from: data) {
            completion(members)
        }
    }
    .resume()
}

POST Requests

Let’s take a look at a POST request using Alamofire:

// 1. Create the function
func addToRoster(member: Member, completion: @escaping (Member) -> Void) {
    // 2. Specify the endpoint
    let endpoint = "<Enter URL String Here>"

    // 3. Define the request body
    let parameters: Parameters = [
	"name": member.name,
	"subteam": member.subteam,
	"position": member.position
    ]
    
    // 4. Create a decoder
    let decoder = JSONDecoder()
    // decoder.dateDecodingStrategy = .iso8601 // Only if needed
    // decoder.keyDecodingStrategy = .convertFromSnakeCase // Only if needed
    
    // 5. Create the request
    AF.request(endpoint, method: .post, parameters: parameters, encoding: JSONEncoding.default)
        .validate()
        .responseDecodable(of: Member.self, decoder: decoder) { response in
	    // 5. Handle the response
            switch response.result {
            case .success(let member):
                print("Successfully added member \(member.name)")
                completion(member)
            case .failure(let error):
                print("Error in NetworkManager.addToRoster: \(error.localizedDescription)")
            }
        }
}

If we were to use URLSession, we need to:

  • Change the httpMethod property of the URLRequest to "POST".

  • Call the setValue function with ("application/json", forHTTPHeaderField: "Content-Type").

  • Set the httpBody property of the URLRequest.

    • The code below uses JSONSerialization to serialize the dictionary parameters to JSON and use it as the request body.

    • Alternatively, we can also use a JSONEncoder to encode our object into JSON, but it won’t be shown here.

// 1. Create the function
func addToRoster(member: Member, completion: @escaping (Member) -> Void) {
    // 2. Specify the endpoint
    let endpoint = "<Enter URL String Here>"

    // 3. Define the request body
    let parameters = [
        "name": member.name,
        "subteam": member.subteam,
        "position": member.position
    ]
    guard let httpBody = try? JSONSerialization.data(
        withJSONObject: parameters,
        options: []
    ) else { return }

    // 4. Create a decoder
    let decoder = JSONDecoder()
    // decoder.dateDecodingStrategy = .iso8601 // Only if needed
    // decoder.keyDecodingStrategy = .convertFromSnakeCase // Only if needed

    // 5. Create a URLRequest
    var urlRequest = URLRequest(url: URL(string: endpoint)!)
    urlRequest.httpMethod = "POST"
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    urlRequest.httpBody = httpBody

    // 6. Create and resume the task
    URLSession.shared.dataTask(with: urlRequest) { data, response, error in
        // 7. Handle the response (you can also do something with `response`)
        guard error == nil, let data else {
            print("Error in NetworkManager.addToRoster: \\(error)")
            return
        }

        if let member = try? decoder.decode(Member.self, from: data) {
            completion(member)
        }
    }
    .resume()
}

Note that we do not have to create the decoder inside of the function call. We can create a JSONDecoder object and store it as a property in our NetworkManager class to be used for all functions. The same can be applied to the endpoint variable containing a String value of our endpoint.

PreviousPOST RequestsNextPersistence + SnapKit

Last updated 1 year ago

Was this helpful?

🌍
4️⃣