ios - 使用 Google Sign In 实现 Google Drive API - iOS

标签 ios objective-c google-drive-api google-oauth google-signin

我正在尝试将 Google Drive API 实现到一个已经在使用 Google Sign In SDK 的项目中。我已将 Google Drive 的范围添加到 GIDSignIn 单例中,但 Drive API 似乎需要用户再次登录。有没有办法在初次登录时通过Google Sign In完成对Google Drive API的授权,而不是强制用户登录两次?

我在这里读过一个类似的问题,Can I use google drive sdk with authentication info from google sign-in sdk on iOS? ,但响应从未从 Google Sign In 返回的 GIDAuthentication 成功创建 Google Drive 所需的 GTMOAuth2Authentication。

最佳答案

我的 iOS 应用遇到了同样的问题,也查看了类似的问题 Can I use Google Drive SDK with sign in information from Google Sign In SDK in iOS .根据 Eran Marom 的回答,我能够将我的 Google 登录凭据转换为 OAuth2 凭据,我用它成功访问了 Apps Script Execute API。

我在 Swift 工作。

在 App Delegate 中:

import GTMOAuth2

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

var window: UIWindow?

//Create an authorization fetcher, which will be used to pass credentials on to the API request
var myAuth: GTMFetcherAuthorizationProtocol? = nil

// [START didfinishlaunching]
func application(application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Initialize sign-in
    var configureError: NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    GIDSignIn.sharedInstance().delegate = self

    let scopes = "https://www.googleapis.com/auth/drive"
    GIDSignIn.sharedInstance().scopes.append(scopes)

    return true
}
//....

func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
            withError error: NSError!) {
    if (error == nil) {

        //sets credentials in fetcher
myAuth = user.authentication.fetcherAuthorizer()

        //...
    } else {
}
//....

在 View Controller 中:

import UIKit
import GoogleAPIClient
import GTMOAuth2

@objc(ViewController)

class ViewController: UITableViewController, GIDSignInUIDelegate {

private let kClientID = "CLIENT ID"
private let kScriptId = "SCRIPT ID"
private let service = GTLService()

override func viewDidLoad() {
    super.viewDidLoad()

    GIDSignIn.sharedInstance().uiDelegate = self
//...
}

func toggleAuthUI() {
    if (GIDSignIn.sharedInstance().hasAuthInKeychain()){

        self.service.authorizer = appDelegate.myAuth
      //...  
    callAppsScript()
    } else {
//...
    }

@objc func receiveToggleAuthUINotification(notification: NSNotification) {
    if (notification.name == "ToggleAuthUINotification") {
        self.toggleAuthUI()
        if notification.userInfo != nil {
            let userInfo:Dictionary<String,String!> =
                notification.userInfo as! Dictionary<String,String!>
            self.statusText.text = userInfo["statusText"]
        }
    }
}

func callAppsScript() {

    let baseUrl = "https://script.googleapis.com/v1/scripts/\(kScriptId):run"
    let url = GTLUtilities.URLWithString(baseUrl, queryParameters: nil)

    // Create an execution request object.
    var request = GTLObject()
    request.setJSONValue("APPS_SCRIPT_FUCTION", forKey: "function")

    // Make the API request.
    service.fetchObjectByInsertingObject(request,
        forURL: url,
        delegate: self,
        didFinishSelector: "displayResultWithTicket:finishedWithObject:error:")
}

func displayResultWithTicket(ticket: GTLServiceTicket,
                             finishedWithObject object : GTLObject,
                                                error : NSError?) {
//Display results...
}

关于ios - 使用 Google Sign In 实现 Google Drive API - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366955/

相关文章:

ios - 如何在 iPhone 导航栏上添加背景图片?

objective-c - 在 Swift 中访问 PFObject 中的项目

ios - 从 NSObject 子类呈现 View Controller

javascript - 使用 javascript 将任何人的文件上传到我的谷歌驱动器

python - 如何使用 Drive API 在 Google 电子表格中获取工作表列表(名称和 "gid")?

ios - 如何比较 KIF 3.1.1 中 UI 中的文本和从 Web 服务接收的文本?

ios - 使用 Swift 在没有 Storyboard的情况下展开 segue

ios - 安装 firebase 后生成推送通知

objective-c - mac应用商店错误

google-drive-api - Google 云端硬盘共享对话框错误 - 'X-Frame-Options' 至 'SAMEORIGIN'