ios - Google Sheets API 根本不起作用?

标签 ios swift google-sheets-api

我现在正在为我的勤工俭学职位开发一个应用程序。一般来说,我对 iOS 编程很陌生,以前从未使用过 API。我不知道自己在做什么,而且 Google 的快速入门也不适合我,这也于事无补。

我完全遵循了快速入门,但现在我在这里不知所措。我到处都有错误,但没有信息来修复它们。 You can see the code here

here is a screenshot of my code with the numerous errors.

这是我在 Xcode 中的代码。

import GoogleAPIClientForREST
import GTMOAuth2
import UIKit

class ViewController: UIViewController {

    private let kKeychainItemName = "Google Sheets API"
    private let kClientID = "<my key>"

    // If modifying these scopes, delete your previously saved credentials by
    // resetting the iOS simulator or uninstall the app.
    private let scopes = [kGTLRAuthScopeSheetsSpreadsheetsReadonly]

    private let service = GTLRSheetsService()
    let output = UITextView()

    // When the view loads, create necessary subviews
    // and initialize the Google Sheets API service
    override func viewDidLoad() {
        super.viewDidLoad()

        output.frame = view.bounds
        output.editable = false
        output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
        output.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]

        view.addSubview(output);

        if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName(
            kKeychainItemName,
            clientID: kClientID,
            clientSecret: nil) {
            service.authorizer = auth
        }

    }

    // When the view appears, ensure that the Google Sheets API service is authorized
    // and perform API calls
    override func viewDidAppear(animated: Bool) {
        if let authorizer = service.authorizer,
            canAuth = authorizer.canAuthorize where canAuth {
            listMajors()
        } else {
            presentViewController(
                createAuthController(),
                animated: true,
                completion: nil
            )
        }
    }

    // Display (in the UITextView) the names and majors of students in a sample
    // spreadsheet:
    // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
    func listMajors() {
        output.text = "Getting sheet data..."
        let spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
        let range = "Class Data!A2:E"
        let query = GTLRSheetsQuery_SpreadsheetsValuesGet
            .queryWithSpreadsheetId(spreadsheetId, range:range)
        service.executeQuery(query,
                             delegate: self,
                             didFinishSelector: "displayResultWithTicket:finishedWithObject:error:"
        )
    }

    // Process the response and display output
    func displayResultWithTicket(ticket: GTLRServiceTicket,
                                 finishedWithObject result : GTLRSheets_ValueRange,
                                 error : NSError?) {

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

        var majorsString = ""
        let rows = result.values!

        if rows.isEmpty {
            output.text = "No data found."
            return
        }

        majorsString += "Name, Major:\n"
        for row in rows {
            let name = row[0]
            let major = row[4]

            majorsString += "\(name), \(major)\n"
        }

        output.text = majorsString
    }



    // Creates the auth controller for authorizing access to Google Sheets API
    private func createAuthController() -> GTMOAuth2ViewControllerTouch {
        let scopeString = scopes.joinWithSeparator(" ")
        return GTMOAuth2ViewControllerTouch(
            scope: scopeString,
            clientID: kClientID,
            clientSecret: nil,
            keychainItemName: kKeychainItemName,
            delegate: self,
            finishedSelector: "viewController:finishedWithAuth:error:"
        )
    }

    // Handle completion of the authorization process, and update the Google Sheets API
    // with the new credentials.
    func viewController(vc : UIViewController,
                        finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) {

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

        service.authorizer = authResult
        dismissViewControllerAnimated(true, completion: nil)
    }

    // Helper for showing an alert
    func showAlert(title : String, message: String) {
        let alert = UIAlertController(
            title: title,
            message: message,
            preferredStyle: UIAlertControllerStyle.Alert
        )
        let ok = UIAlertAction(
            title: "OK",
            style: UIAlertActionStyle.Default,
            handler: nil
        )
        alert.addAction(ok)
        presentViewController(alert, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

我是否缺少图书馆或其他东西?

最佳答案

您复制/编写的代码似乎是 Swift 2.x,但您正在使用 Swift 3 进行编译。

在 Xcode 中,编辑 -> 转换 -> 到当前 Swift 语法... 可能会在一定程度上解决。

关于ios - Google Sheets API 根本不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42955542/

相关文章:

google-sheets - 使用 Sheets API 调用隐藏列

java - 通过 Google Sheets api v4 将新工作表添加到现有电子表格

Android 和 iOS Firebase 数据库数据合并

ios - Swift - 约束 - 动态标签宽度

objective-c - 使用 Interface Builder 硬编码 UITableView : is it possible?

iOS UIDocumentInteractionController,presentOptionsMenuFromRect 失败,但 presentOpenInMenuFromRect 有效

ios - 使用 OpenCV 图像识别为 Objective-C 自定义视频摄像头应用程序添加亮度/ Gamma 控制

ios - 父 View 中的状态更改创建子 ViewModel 的新实例

ios - 当 View 在 ScrollView 内时 onTapGesture 不工作?

javascript - 如何使用 Google 脚本获取特定工作表的链接?