Skip to content

Instantly share code, notes, and snippets.

@danielsaidi
Last active October 15, 2024 09:54
Show Gist options
  • Save danielsaidi/f57cd1a854be7e1a4b656b604835d681 to your computer and use it in GitHub Desktop.
Save danielsaidi/f57cd1a854be7e1a4b656b604835d681 to your computer and use it in GitHub Desktop.
This gist contains a GoogleSheet implementation for Swift
import Foundation
struct GoogleSheet {
/// Fetch CSV parsed data from a certain sheet.
///
/// - Parameters:
/// - id: The unique sheet ID.
/// - name: The name of the sheet to parse, by default the first.
static func csvData(
fromSheet id: String,
name: String = ""
) async throws -> [[String]] {
let url = "https://docs.google.com/spreadsheets/d/\(id)/gviz/tq?tqx=out:csv&sheet=\(name)"
guard let url = URL(string: url) else {
throw NSError(domain: "Invalid URL", code: 0, userInfo: nil)
}
let data = try await URLSession.shared.data(from: url).0
let string = String(data: data, encoding: .utf8)
guard let string else {
throw NSError(domain: "Unable to convert data to string", code: 0, userInfo: nil)
}
let rows = string.components(separatedBy: "\n")
let parsedData = rows.map { $0.components(separatedBy: ",") }
return parsedData
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment