What’s the best way to use HTTP requests in your iOS app?

ByungwookAn
3 min readSep 22, 2023

--

image source : https://developer.apple.com/support/

Intro

Most iOS apps use HTTP requests in the app. Among the way that HTTP request, Alamofire, and URLSession is the most popular structure to set HTTP request. Today, I’ll talk about making network requests in the iOS app using Alamofire and URLSession. and then, I’ll talk about which one is suited for your app.

Point to note

Before compare between Alamofire and URLSession, We have to know various HTTP methods for making network requests.

  1. .GET: Retrieve resources from the server.
  2. .POST: Send data to the server, typically used for creating new resources.
  3. .PUT: Update an existing resource on the server.
  4. .PATCH: Partially update an existing resource on the server.
  5. .DELETE: Delete a resource from the server.

Alamofire

First, Alamofire. Alamofire is a 3rd party library that provides a high-level API for making networks. Alamofire is based on URLSession. You can import Alamofire through SPM, Carthage, and Cocoapods.

Here’s the sample code of Alamofire.

Model

import Foundation

struct NewsResponse: Codable {
let articles: [Article]
}

struct Article: Codable {
let title: String
let description: String
}

ViewModel

import Foundation
import Alamofire

class ViewModel: ObservableObject {

@Published var article = [Article]()

init(article: [Article] = []) {
self.article = article
}

func fetchData() {
if let url = URL(string: "your url") {
AF.request(url, method: .get, encoding: URLEncoding.default).responseDecodable(of: NewsResponse.self) { response in
switch response.result {
case .success(let results):
DispatchQueue.main.async {
self.article = results.articles
}
case .failure(let error):
print(error)
}
}
}
}
}

View

import SwiftUI

struct ContentView: View {

@ObservedObject var viewModel = ViewModel()

var body: some View {
NavigationView {
List(viewModel.article, id: \.title) { article in
VStack(alignment: .leading) {
Text(article.title)
.font(.headline)
Text(article.description)
.font(.subheadline)
}
}
.navigationBarTitle("Today's news")
.onAppear {
self.viewModel.fetchData()
}
}
}
}

URLSession

URLSession is a part of the Foundation framework in Swift and is provided by Apple. So you don’t have to import a library like Alamofire. It offers a lower-level API for handling network requests.

Here’s the sample code of URLSession.

Model

import Foundation

struct NewsResponse: Codable {
let articles: [Article]
}

struct Article: Codable {
let title: String
let description: String
}

ViewModel


import Foundation

class ViewModel: ObservableObject {

@Published var article = [Article]()

init (article: [Article] = []) {
self.article = article
}

func fetchData() {
if let url = URL(string: "your url") {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error == nil {
let decoder = JSONDecoder()
if let safeData = data {
do {
let results = try decoder.decode(NewsResponse.self, from: safeData)
DispatchQueue.main.async {
self.article = results.articles
}
} catch {
print(error)
}
}
}
}
task.resume()
}
}
}

View

import SwiftUI

struct ContentView: View {

@ObservedObject var viewmodel = ViewModel()

var body: some View {
NavigationView {
List(viewmodel.article, id: \.title) { article in
VStack(alignment: .leading) {
Text(article.title)
.font(.headline)
Text(article.description)
.font(.subheadline)
}
.navigationBarTitle("Today's news")
}
.onAppear {
self.viewmodel.fetchData()
}
}
}
}

What’s the difference between Alamofire and URLSession?

Dependencies

Alamofire: Alamofire is a 3rd party library. You can import Alamofire through SPM, Carthage, and Cocoapods. You need to manage its updates and ensure compatibility with your project.

URLSession: URLSession is a part of the Swift Foundation framework and doesn’t require external dependencies. It’s available by default in iOS, macOS, watchOS, and tvOS applications.

Abstraction

Alamofire: It abstracts away many of the low-level details of URLSession. So you can make the code more readable and manageable.

URLSession: It offers a lower-level API for handling network requests. So it can be beneficial for complex or custom networking scenarios.

Features

Alamofire: It provides a more convenient and expressive syntax for sending requests.

URLSession: It is more hard to send requests than Alamofire.But you can make a complex and detailed networking system with URLSession.

Conclusion

Alamofire and URLSession have their own advantages. These two ways to use HTTP request is stable and have many examples to be found. It’s hard to conclude that one of the two ways to use HTTP is the correct answer. So you must choose wisely through the difference between Alamofire and URLSession I describe.

Source

--

--