在swift中添加Google日历活动

我正在尝试使用Swift中的API创建Google日历活动。 我现在有点失去了如何解决这个问题。 更具体地说,创建一个GTLRCalendar_Event对象以通过GTLRCalendarQuery_EventsInsert.query() 。 有什么方法可以解决这个问题?

我写了以下代码

 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) 

我在Swift 4中使用它。我基于谷歌的Java代码示例,因为它是最相似的。 我希望这能回答你所有的问题。 我相信有一个更漂亮的方法可以做到这一点,但我不知道。 🙂

 //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 ) }