I am trying to fetch Calendar events to my iOS application. So, for that I have create a project in Google developers console and got Client ID, ApiKey.
And installed pods with
pod 'GoogleAPIClient/Calendar', '~> 1.0.2' pod 'GTMOAuth2', '~> 1.1.0' pod 'Google/SignIn'
And after signing to Gmail, its asking permission to access Calendar, till that working fine, but, while fetching the events showing following error.
error NSError domain: "com.google.GTLJSONRPCErrorDomain" - code: 401 0x0000604000646330
And my code is follows
private let scopes = [kGTLAuthScopeCalendar]
private let service = GTLServiceCalendar()
private let kApiKey = "someKey"
let output = UITextView()
private let kKeychainItemName = "Google Calendar API"
private let kClientID = "SomeID"
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if (error == nil) {
} else {
print("\(error.localizedDescription)")
}
if user != 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
}
print("\(user)")
service.authorizer = user.authentication.fetcherAuthorizer()
fetchEvents()
}
}
func fetchEvents() {
let query = GTLQueryCalendar.queryForEventsList(withCalendarId: "primary")
query?.maxResults = 10
query?.singleEvents = true
query?.orderBy = kGTLCalendarOrderByStartTime
service.executeQuery(
(query)!,
delegate: self,
didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
}
// Display the start dates and event summaries in the UITextView
@objc 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.")
}
}
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Thank You", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().clientID = kClientID
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = scopes
GIDSignIn.sharedInstance().signIn()
GIDSignIn.sharedInstance().delegate = self
service.apiKey = kApiKey
}
Even I checked few forums, I did not get any solution for this.
Can anyone suggest me where I am getting wrong?