1

在我使用 Swift 学习 Google Sheets API 的过程中,我想将单个范围写入电子表格。

查看快速入门 iOS 指南基本写作示例,我附带了以下代码:

func constructAndSendAQuery() {
    let baseUrl = "https://sheets.googleapis.com/v4/spreadsheets"
    let spreadsheetId = "1FhbBdEvpcyHsdfgsdft65eDGHre2fLVki5ZolMmZaRs"
    let range = "Sales!A31:C31"
    let url = baseUrl + "/" + spreadsheetId + "/values/" + range
    let params = ["valueInputOption": "RAW"]
    let fullUrl = GTLUtilities.URLWithString(url, queryParameters: params)

    let body = GTLObject()
    body.JSON = ["majorDimension":"ROWS",
                 "values": ["One", "Two", "Three"]]

    service.fetchObjectByInsertingObject(body, 
                                         forURL: fullUrl,
                                         delegate: self, 
                                         didFinishSelector: #selector(ViewController.processTheResponse(_:finishedWithObject:error:)))
}

不知道我做错了什么,但我收到错误消息:“在此服务器上找不到请求的 URL”。

4

3 回答 3

1

正如@sam-berlin 提到的,我应该使用fetchObjectByUpdatingObject而不是fetchObjectByInsertUpdating.

但是还有一个小错误/错字。在构造 JSON 时,我丢失了一对方括号,并收到关于无效值的错误。

工作代码如下所示:

func constructAndSendARequest() {

    let baseUrl = "https://sheets.googleapis.com/v4/spreadsheets"
    let spreadsheetId = "1FhbBdEvpsfgzb3Akn1opmru0iresdfglbki5ZMmZaRs"
    let range = "Sales!A3:D3"
    let url = baseUrl + "/" + spreadsheetId + "/values/" + range
    let params = ["valueInputOption": "RAW"]
    let fullUrl = GTLUtilities.URLWithString(url, queryParameters: params)


    let body = GTLObject()
    body.JSON = ["range": range,
                 "majorDimension": "ROWS",
                 "values": [["One", "Two", "Three"]]]

    service.fetchObjectByUpdatingObject(body, forURL: fullUrl, delegate: self, didFinishSelector: #selector(ViewController.processTheResponse(_:finishedWithObject:error:)))   
}

也可以使用service.fetchObjectByUpdatingObject(body, forURL: fullUrl, completionHandler: nil)而不处理响应。

于 2016-06-14T23:00:27.003 回答
0

如果有人需要,我在这里回答了类似的问题。您可以使用该GTLRSheets_ValueRange()对象并GTLRSheetsQuery_SpreadsheetsValuesUpdate.query(withObject:通过 Google Sheets API 创建或更新任何单元格。

let service = GTLRSheetsService()
service.authorizer = GIDSignIn.sharedInstance().currentUser.authentication.fetcherAuthorizer()
service.apiKey = Constants.GOOGLE_SPEADSHEET_API_KEY
let rowIndex:Int = job.rowIndex
let range = "Employee List!C\(rowIndex):C\(rowIndex)"
let valueRange = GTLRSheets_ValueRange()
valueRange.range = "Employee List!C\(rowIndex):C\(rowIndex)"
valueRange.values = [[job.jobTitle!]]
valueRange.majorDimension = "COLUMNS"

let query = GTLRSheetsQuery_SpreadsheetsValuesUpdate.query(withObject: valueRange, spreadsheetId:  Constants.SPREAD_SHEET_ID, range: range)
query.valueInputOption = "USER_ENTERED"

service.executeQuery(query) { (ticket, response, error) in
    print(response)

}
于 2018-09-19T20:49:08.160 回答
0

根据GTLService 代码fetchObjectByInsertUpdating执行一个POST,而这个请求需要一个PUT. 似乎fetchObjectByUpdatingObject应该做 a PUT,所以试试吧。

于 2016-06-14T14:38:52.710 回答