Write to Google Sheets in Swift

Viewed 1411

I'm really confused how to write to an excel sheet, that is public. So far I have downloaded Alamofire and GoogleAPIClientForREST cocoapods. So I was wondering, if I want to write to the sheet do I first need to implement a google sign in or can I just send data over using Alamofire. I am super lost so If someone can help me that would be great.

Google sheet: https://docs.google.com/spreadsheets/d/1zJR0uk6Pb6BuxJihFyxwe4ipQdBY4E9FFR74geBj8p0/edit#gid=0

func makeAndSendRequest() {
    let baseUrl = "https://sheets.googleapis.com/v4/spreadsheets"
    let spreadsheetId = "1zJR0uk6Pb6BuxJihFyxwe4ipQdBY4E9FFR74geBj8p0"
    let params = ["valueInputOption": "RAW"]
    let range = "Studen!A3:B3"
    //need to add params
    let url = baseUrl + "/" + spreadsheetId + "/values/" + range + "/valueInputOption=RAW/"

    let fullUrl = URL(string: url)!

    //my values
    let requestParams = [
        "values": [
            1,
            2
        ]
    ]


    //my auth is after Bearer so "Bearer 901390"
    let header = ["Authorization":"Bearer "]
    let requestURL = "https://sheets.googleapis.com/v4/spreadsheets/\(spreadsheetId)/values/\(range)?valueInputOption=RAW"
    let req = Alamofire.request(requestURL, method: .put, parameters: requestParams, encoding: JSONEncoding.default,headers: header)
    req.responseJSON { response in debugPrint(response) }

}
1 Answers

Try to fix this first.

valueInputOption is a query parameter, see: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update

You URL should at least be:

let url = baseUrl + "/" + spreadsheetId + "/values/" + range + "?valueInputOption=RAW"

next you need to fix your request body, range is required per document here: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update

{ "range": "A3:B3", "values": [ [ 1, 2 ] ] }

This range should be same as your range in your query parameter, say Sheet1!:A3:B3 as in your query parameter.

Note that it starts with the sheet name, it should not be "studen"

I have used the playground tool on the same page and able to call the api to change the data in your spreadsheet.

At the end I am getting 200 response code and following json: { "spreadsheetId": "1zJR0uk6Pb6BuxJihFyxwe4ipQdBY4E9FFR74geBj8p0", "updatedRange": "Sheet1!A3:B3", "updatedRows": 1, "updatedColumns": 2, "updatedCells": 2 }

----- Edit ----- As you asked, the API needs Oauth token, the framework to handle this is actually called G Suite

Please find the guide here: https://developers.google.com/gsuite/guides/ios

Related