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)

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)
}

RELATED:


Image

@samwize

¯\_(ツ)_/¯

Back to Home