← Back to Tutorials

9. Networking & Communication

Networking & Communication

URLSession

Foundation's built-in networking API for HTTP requests:

// GET request
let url = URL(string: "https://api.example.com/users")!
let task = URLSession.shared.dataTask(with: url) {
    data, response, error in
    guard let data = data, error == nil else { return }
    if let json = try? JSONSerialization.jsonObject(with: data) {
        print(json)
    }
}
task.resume()

// POST request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body = ["name": "Alice", "email": "alice@example.com"]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let postTask = URLSession.shared.dataTask(with: request) {
    data, response, error in
    // Handle response
}
postTask.resume()

Alamofire

Popular third-party networking library (add via Swift Package Manager):

import Alamofire

AF.request("https://api.example.com/users",
    method: .get).responseJSON { response in
    switch response.result {
    case .success(let data):
        print(data)
    case .failure(let error):
        print(error)
    }
}

Codable & JSON

Swift's native JSON encoding/decoding with Codable:

struct User: Codable {
    let id: Int
    let name: String
    let email: String
}

// Decode
let decoder = JSONDecoder()
let users = try decoder.decode([User].self, from: jsonData)

// Encode
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(user)

WebSocket

Real-time two-way communication:

let session = URLSession(configuration: .default)
let webSocketTask = session.webSocketTask(
    with: URL(string: "wss://echo.example.com")!)

webSocketTask.resume()

// Send
webSocketTask.send(.string("Hello")) { error in }

// Receive
webSocketTask.receive { result in
    switch result {
    case .success(let message):
        switch message {
        case .string(let text):
            print(text)
        default: break
        }
    case .failure(let error):
        print(error)
    }
}

Sending Email, SMS & Phone Calls

Use MFMailComposeViewController and MFMessageComposeViewController from MessageUI framework:

import MessageUI

// Email
if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.setToRecipients(["support@example.com"])
    mail.setSubject("App Feedback")
    mail.setMessageBody("Hello, ", isHTML: false)
    present(mail, animated: true)
}

// Open phone dialer
guard let url = URL(string: "tel://+1234567890") else { return }
UIApplication.shared.open(url)
Practice Task: Build a "Weather App" that fetches weather data from a public API (e.g., OpenWeatherMap). Display temperature, humidity, and conditions. Use Codable to parse JSON. Add a "Share" button that opens a mail compose sheet with the weather data. Implement pull-to-refresh using UIRefreshControl.