read

With Swift 5.5 new concurrency syntax, many frameworks have been updated. This post cover the basic URLSession operations.

GET

let url = URL(string: "https://query2.finance.yahoo.com/v10/finance/quoteSummary/AAPL?modules=price")!
let (data, response) = try await URLSession.shared.data(from: url)

// Handle response etc by throwing error
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
    throw MyError.notOk
}

let content = String(data: data, encoding: .utf8)!
print(content)

POST

let url = URL(string: "https://samwize.com/api/example")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let payload = "id=1234".data(using: .utf8)! // query string in payload
let (data, response) = try await URLSession.shared.upload(for: request, from: payload)

Download

let url = URL(string: "https://samwize.com/images/ios-support-matrix.png")!
let (savedLocalUrl, response) = try await URLSession.shared.download(from: url)
try FileManager.default.moveItem(at: savedLocalUrl, to: newLocation)

Query String in the URL

var url = URL(string: "https://query2.finance.yahoo.com/v10/finance/quoteSummary/AAPL")!
url.append(queryItems: [
    URLQueryItem(name: "modules", value: "price")
])

Stream bytes

let url = URL(string: "https://samwize.com")!
let (bytes, response) = try await URLSession.shared.bytes(from: url)

for try await line in bytes.lines {
    print(line)
}

Caching

There are 2 ways to specify the cache policy.

// 1. In URLRequest
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
// 2. Configure your own session
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
let session = URLSession(configuration: configuration)

RELATED:


Image

@samwize

¯\_(ツ)_/¯

Back to Home