Reputation: 11
I am trying to create a Google Calendar event using the API in Swift. I am kind of lost at the moment in how to go about that. More specifically creating a GTLRCalendar_Event
object to pass through GTLRCalendarQuery_EventsInsert.query()
. Any way to go about this?
I've written the following code
var newEvent: GTLRCalendar_Event = GTLRCalendar_Event()
newEvent.summary = name
//set GTLRDateTimes
var startTime: GTLRDateTime = GTLRDateTime(date:startTimeObject!, offsetMinutes: offsetMinutes)
var endTime: GTLRDateTime = GTLRDateTime(date:endTimeObject!, offsetMinutes: offsetMinutes)
newEvent.reminders?.useDefault = 0
newEvent.start?.dateTime = startTime
newEvent.end?.dateTime = endTime
let service: GTLRCalendarService = GTLRCalendarService()
let query:GTLRCalendarQuery_EventsInsert = GTLRCalendarQuery_EventsInsert.query(withObject: newEvent, calendarId:"primary")
service.executeQuery(query, completionHandler: {(_ callbackTicket: GTLRServiceTicket, _ event: GTLRCalendar_Event, _ callbackError: Error?) -> Void in
print("executed query")
if callbackError == nil {
print("added")
print(newEvent.summary);
}
else {
print("add failed")
print(callbackError)
}
} as? GTLRServiceCompletionHandler)
Upvotes: 1
Views: 4944
Reputation: 507
I got this working in SwiftUI using GoogleSignIn and GoogleAPIClientForREST packages. First, the app signs the user in, and then it uses GTLRCalendarService() to insert a calendar event.
Code snippet for the sign-in logic
GIDSignIn.sharedInstance.signIn(
withPresenting: getRootViewController()!) { signInResult, error in
if signInResult == nil {
return
}
else if error != nil {
return
}
// If sign-in succeeded, extract user info.
user = signInResult!.user
}
} // handleSignInButton()
func getRootViewController() -> UIViewController? {
return UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
.first { $0.isKeyWindow }?.rootViewController
}
Code snippet for adding a calendar event. Note the line needed to initialize the authorizer: service.authorizer = user.fetcherAuthorizer
func addEventoToGoogleCalendar(summary : String, description :String, startTime : String, endTime : String) {
let SRC = self.SRC + ".addEventoToGoogleCalendar"
print("\(SRC): Called")
let calendarEvent = GTLRCalendar_Event()
calendarEvent.summary = "\(summary)"
calendarEvent.descriptionProperty = "\(description)"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"
let startDate = dateFormatter.date(from: startTime)
let endDate = dateFormatter.date(from: endTime)
guard let toBuildDateStart = startDate else {
print("Error getting start date")
return
}
guard let toBuildDateEnd = endDate else {
print("Error getting end date")
return
}
calendarEvent.start = buildDate(date: toBuildDateStart)
calendarEvent.end = buildDate(date: toBuildDateEnd)
let insertQuery = GTLRCalendarQuery_EventsInsert.query(withObject: calendarEvent, calendarId: "primary")
let service = GTLRCalendarService()
service.authorizer = user.fetcherAuthorizer
service.executeQuery(insertQuery) { (ticket, object, error) in
if error == nil {
print("\(SRC): Event inserted")
} else {
print("\(SRC): error = \(error!)|")
}
}
// Helper to build date
func buildDate(date: Date) -> GTLRCalendar_EventDateTime {
let datetime = GTLRDateTime(date: date)
let dateObject = GTLRCalendar_EventDateTime()
dateObject.dateTime = datetime
return dateObject
}
} // addEventoToGoogleCalendar()
A full example is available in github.
Upvotes: 0
Reputation: 114
I was facing the same problem during the lack of resources at this topic, those are the steps
->configure your app with google calendar account
1-go to https://console.developers.google.com/ add a new project with app bundle id and name
2- go to dashboard click Enable APIS AND SERVICES then choose a calendar API Service and enable It.
3-choose credentials from the side menu and click CREATE CREDENTIALS Link from top of the page and add OAuth Client ID
4-open firebase console https://console.firebase.google.com/u/0/
5- click add project and choose your existing app and continue
6- follow the steps here https://firebase.google.com/docs/ios/setup until download "GoogleService-Info.plist" and add it to your app -> write code to add an event to google calendar
1-follow those steps to add google sign-in https://developers.google.com/identity/sign-in/ios/sign-in?ver=swift
2- // Create an event to the Google Calendar's user
func addEventoToGoogleCalendar(summary : String, description :String, startTime : String, endTime : String) {
let calendarEvent = GTLRCalendar_Event()
calendarEvent.summary = "\(summary)"
calendarEvent.descriptionProperty = "\(description)"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"
let startDate = dateFormatter.date(from: startTime)
let endDate = dateFormatter.date(from: endTime)
guard let toBuildDateStart = startDate else {
print("Error getting start date")
return
}
guard let toBuildDateEnd = endDate else {
print("Error getting end date")
return
}
calendarEvent.start = buildDate(date: toBuildDateStart)
calendarEvent.end = buildDate(date: toBuildDateEnd)
let insertQuery = GTLRCalendarQuery_EventsInsert.query(withObject: calendarEvent, calendarId: "primary")
service.executeQuery(insertQuery) { (ticket, object, error) in
if error == nil {
print("Event inserted")
} else {
print(error)
}
}
}
// Helper to build date
func buildDate(date: Date) -> GTLRCalendar_EventDateTime {
let datetime = GTLRDateTime(date: date)
let dateObject = GTLRCalendar_EventDateTime()
dateObject.dateTime = datetime
return dateObject
}
// Helper for showing an alert
func showAlert(title : String, message: String) {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: UIAlertController.Style.alert
)
let ok = UIAlertAction(
title: "OK",
style: UIAlertAction.Style.default,
handler: nil
)
alert.addAction(ok)
present(alert, animated: true, completion: nil)
}
here is the GitHub link https://github.com/emanShedeed/writeEventToGoogleCalendar
Upvotes: 0
Reputation: 41
I got this to work in Swift 4. I based it on the Java code example that Google has because that one was the most similar. I hope this answers all of your questions. I am sure there is a prettier way to do this, but I don't know it. :)
//Declares the new event
var newEvent: GTLRCalendar_Event = GTLRCalendar_Event()
//this is setting the parameters of the new event
newEvent.summary = ("Google I/O 2015")
newEvent.location = ("800 Howard St., San Francisco, CA 94103")
//I ran into some problems with the date formatting and this is what I ended with.
//Start Date. The offset adds time to the current time so if you run the program at 12:00 then it will record a time of 12:05 because of the 5 minute offset
let startDateTime: GTLRDateTime = GTLRDateTime(date: Date(), offsetMinutes: 5)
let startEventDateTime: GTLRCalendar_EventDateTime = GTLRCalendar_EventDateTime()
startEventDateTime.dateTime = startDateTime
newEvent.start = startEventDateTime
print(newEvent.start!)
//Same as start date, but for the end date
let endDateTime: GTLRDateTime = GTLRDateTime(date: Date(), offsetMinutes: 50)
let endEventDateTime: GTLRCalendar_EventDateTime = GTLRCalendar_EventDateTime()
endEventDateTime.dateTime = endDateTime
newEvent.end = endEventDateTime
print(newEvent.end!)
let service: GTLRCalendarService = GTLRCalendarService()
//The query
let query =
GTLRCalendarQuery_EventsInsert.query(withObject: newEvent, calendarId:"Past your calendar ID here this is specific to the calendar you want to edit and can be found under the google calendar settings")
//This is the part that I forgot. Specify your fields! I think this will change when you add other perimeters, but I need to review how this works more.
query.fields = "id";
//This is actually running the query you just built
self.service.executeQuery(
query,
completionHandler: {(_ callbackTicket:GTLRServiceTicket,
_ event:GTLRCalendar_Event,
_ callbackError: Error?) -> Void in}
as? GTLRServiceCompletionHandler
)
}
Upvotes: 3