如何使用Google表格API V4从Swift 2.2创建新的Google表格?

时间:2016-08-16 15:36:27

标签: ios swift google-sheets-api

我正在尝试使用Google表格API V4和Swift 2.2创建新的Google工作表。我希望得到一个带有spreadsheetID的返回对象。我想提供一个标题。我的猜测是我没有正确格式化URL参数。提前感谢任何可以提供帮助的人!

import GoogleAPIClient
import GTMOAuth2
import UIKit

class ViewController: UIViewController {
     private let kKeychainItemName = "Google Sheets API"

    private let kClientID = "blah-blahblahblah.apps.googleusercontent.com"
    private let scopes = ["https://www.googleapis.com/auth/spreadsheets"]
    private let service = GTLService()

...
...
...

 func createNewSheet() {
        print("Creating New Sheet ...\n")
        let baseUrl = "https://sheets.googleapis.com/v4/spreadsheets"
        let params = ["title": "NewSheet"]
        let fullUrl = GTLUtilities.URLWithString(baseUrl,queryParameters: params)

        service.fetchObjectWithURL(fullUrl,
                                   objectClass: GTLObject.self,
                                   delegate: self,
                                   didFinishSelector: #selector(ViewController.displayResultWithTicket2(_:finishedWithObject:error:))
        )
    }

    func displayResultWithTicket2(ticket: GTLServiceTicket,
                                 finishedWithObject object : GTLObject,
                                                    error : NSError?) {

        if let error = error {
            showAlert("Error", message: error.localizedDescription)
            return
        }

        print(object)

        ...
        ...

1 个答案:

答案 0 :(得分:0)

要在Sheetsv4中add a new sheet,请使用:

POST https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate

URI请求正文:

{
  "requests": [
    {
      "addSheet": {
        "properties": {
          "title": "Deposits",
          "gridProperties": {
            "rowCount": 20,
            "columnCount": 12
          },
          "tabColor": {
            "red": 1.0,
            "green": 0.3,
            "blue": 0.4
          }
        }
      }
    }
  ]
}

如何在Swift中执行此操作?

利用NSURLNSURLRequestNSURLSessionNSURLConnection

等HTTP请求

使用NSURLSession

NSURLSessionDataTask初始化NSURL对象和NSURLSession。然后使用resume()运行任务。

let url = NSURL(string: "http://www.stackoverflow.com")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}

task.resume()

该代码段的this thread的积分。