在我使用Swift学习Google Sheets API的过程中,我想在电子表格中编写一个范围。
展望Quickstart iOS Guide和Basic Writing examples我附带了这段代码:
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:)))
}
不知道我做错了什么,但收到了错误消息:"在此服务器上找不到请求的网址"。
答案 0 :(得分: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)
而不处理响应。
答案 1 :(得分:0)
根据GTLService code,fetchObjectByInsertUpdating
执行POST
,而此请求需要PUT
。似乎fetchObjectByUpdatingObject
应该PUT
,所以请尝试相反。
答案 2 :(得分:0)
如果有人需要,我就类似的问题回答了here。
您可以使用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)
}