iOS API上的Gmail API只读属性403禁止错误

时间:2016-12-20 17:59:06

标签: ios oauth oauth-2.0 google-oauth gmail-api

我关注this url

import GoogleAPIClientForREST
import GTMOAuth2

在视图控制器中,我添加了一个按钮来启动gmail api配置

@IBOutlet weak var btnSyncGmail: UIButton! //button to configure Gmail API

我在这里提到了oAuth的客户端ID,我注释隐藏了******

中的客户端ID
private let kClientID = "*******************.apps.googleusercontent.com"
private let kRedirectURI = "com.googleusercontent.apps.***********************:/oauthredirect"

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

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

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

    // Do any additional setup after loading the view.
}

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

// Construct a query and get a list of upcoming labels from the gmail API
func fetchLabels() {
    output.text = "Getting labels..."

    let query = GTLRGmailQuery_UsersLabelsList.query(withUserId: "me")
    service.executeQuery(query,
                         delegate: self,
                         didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:))
    )
}

// Display the labels in the UITextView
func displayResultWithTicket(ticket : GTLRServiceTicket,
                             finishedWithObject labelsResponse : GTLRGmail_ListLabelsResponse,
                              error : NSError?) {

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

    var labelString = ""

    if (labelsResponse.labels?.count)! > 0 {
        labelString += "Labels:\n"
        for label in labelsResponse.labels! {
            labelString += "\(label.name!)\n"
        }
    } else {
        labelString = "No labels found."
    }

    output.text = labelString

}


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

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

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

    service.authorizer = authResult
    dismiss(animated: 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)
    present(alert, animated: true, completion: nil)
}

btnSyncGmail按钮操作

@IBAction func startSyncingGmail(_ sender: UIButton) {

    if let authorizer = service.authorizer,
        let canAuth = authorizer.canAuthorize , canAuth {
        fetchLabels()
    } else {
        present(
            createAuthController(),
            animated: true,
            completion: nil
        )
    }

    output.frame = view.bounds
    output.isEditable = false
    output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
    output.autoresizingMask = [.flexibleHeight, .flexibleWidth]

    view.addSubview(output);

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

我运行应用程序;点击按钮后,加载程序在几秒钟后启动,我将“HTTP 403禁止”访问错误作为输出。我不知道为什么我得到这个。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

403 Forbidden错误是由于作用域错误造成的,请尝试仔细检查是否使用了正确的作用域。检查此Gmail scopes以了解每个范围的说明。使用此https://mail.google.com/范围可在Gmail API中获得完全或完全访问权限。此外,请不要忘记在开发者控制台中启用Gmail API和您正在使用的其他API。