最近Google OAuth政策的变化后,这个问题有一个解决方法。
在集成Google登录并启用Google日历API后,我能够使用Google日历API获取和添加日历事件。我们只需要为GTLServiceCalendar设置授权器,该授权器是在Google登录后获得的。
service.authorizer = user.authentication.fetcherAuthorizer()
以下是Google GIDSignIn的代码片段,接着便是获取日历事件。
import GoogleAPIClient
import GTMOAuth2
import UIKit
import GoogleSignIn
class ViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate {
private let kApiKey = "AIzaXXXXXXXXXXXXXXXXXXXXXXX"
private let scopes = [kGTLAuthScopeCalendar]
private let service = GTLServiceCalendar()
override func viewDidLoad() {
super.viewDidLoad()
service.apiKey = kApiKey
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = scopes
GIDSignIn.sharedInstance().signIn()
GIDSignIn.sharedInstance().delegate = self
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if user != nil {
print("\(user)")
service.authorizer = user.authentication.fetcherAuthorizer()
fetchEvents()
}
}
func fetchEvents() {
let query = GTLQueryCalendar.queryForEventsList(withCalendarId: "primary")
query?.maxResults = 20
query?.singleEvents = true
query?.orderBy = kGTLCalendarOrderByStartTime
service.executeQuery(query!, delegate: self, didFinish: #selector(ViewController.displayResultWithTicket(ticket:finishedWithObject:error:)))
}
func displayResultWithTicket(
ticket: GTLServiceTicket,
finishedWithObject response : GTLCalendarEvents,
error : NSError?) {
if let error = error {
showAlert(title: "Error", message: error.localizedDescription)
return
}
var eventString = ""
if let events = response.items(), !events.isEmpty {
for event in events as! [GTLCalendarEvent] {
print(event)
}
} else
print("No upcoming events found.")
}
}
}
这是我的凭据部分在Google Dev控制台中的显示方式。