1

I am attempting to create a new google sheet using the Google Sheets API V4 and Swift 2.2. I am hoping to get a return object with the spreadsheetID. I would like to provide a title. My guess is that i am not formatting the URL parameter correctly. Thanks in advance for anyone who can help!

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)

        ...
        ...
AnthonyD
  • 11
  • 1

1 Answers1

0

To add a new sheet in Sheetsv4, use:

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

URI request body:

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

How to do this in Swift?

Make use of HTTP requests like NSURL, NSURLRequest and NSURLSession or NSURLConnection

Using NSURLSession

Initialize an NSURL object and an NSURLSessionDataTask from NSURLSession. Then run the task with 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()

Credits to this thread for that snippet.

Community
  • 1
  • 1
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56