使用Google登录实施Google云端硬盘API - iOS

时间:2016-04-01 22:45:36

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

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

我在这里已经阅读了类似的问题,Can I use google drive sdk with authentication info from google sign-in sdk on iOS?,但是该响应从未成功创建Google云端硬盘所需的GTMOAuth2身份验证,而这是Google登录所返回的GID身份验证。

1 个答案:

答案 0 :(得分:1)

我的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。

我在斯威夫特工作。

在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 {
}
//....

在ViewController中:

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...
}