Search code examples
swiftgoogle-apps-scriptgoogle-sheetsdownloadnsfilemanager

How to download CSV file from the web with dowload URL Swift


So I need to get the data from a google sheet (which I'm trying to generate the link for, not sure), but I have a dummy link which works. I wrote this code to download the CSV file from the spreadsheet and then parse it into an array. When I print the parsed CSV, I simply get an array with one element which is App/... some location in the system.

 func getDataFromSheet(){
        let urlString = "https://docs.google.com/spreadsheets/d/e/2PACX-1vT2-wSYyvNPeF7W3HGyw_MPhMXfuQwzBMAx8SjBOWR5PlZpeTZUCmKuPo044wYKLpweZe7ucUVl0yT5/pub?gid=1025030631&single=true&output=csv"

        // 2
        if let imageUrl = URL(string: urlString) {
            // 3
            URLSession.shared.downloadTask(with: imageUrl) { (tempFileUrl, response, error) in
                
                // 4
                if let imageTempFileUrl = tempFileUrl {
                    do {
                        
                  
                            let content = try String(data: imageTempFileUrl.dataRepresentation, encoding: .utf8)
                            let parsedCSV: [String] = content!.components(
                                separatedBy: "\n"
                            ).map{ $0.components(separatedBy: ",")[0] }
                        print(parsedCSV.description)
                        
                        
                    
                        
                    } catch {
                        print("Error")
                    }
                }
            }.resume()
        }
    }

Solution

  • try this example code, works for me:

    func getDataFromSheet() {
        let urlString = "https://docs.google.com/spreadsheets/d/e/2PACX-1vT2-wSYyvNPeF7W3HGyw_MPhMXfuQwzBMAx8SjBOWR5PlZpeTZUCmKuPo044wYKLpweZe7ucUVl0yT5/pub?gid=1025030631&single=true&output=csv"
        
        guard let url = URL(string: urlString) else { print("error"); return }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data {
                if let content = String(data: data, encoding: .utf8) {
                    let parsedCSV: [String] = content.components(separatedBy: "\n")
                    // all data
                    print(parsedCSV, "\n")
                    // first line
                    print(parsedCSV.map{ $0.components(separatedBy: ",")}[0], "\n")
                    // second line
                    print(parsedCSV.map{ $0.components(separatedBy: ",")}[1], "\n")
                }
            }
        }.resume()
    }